Java design mode -- sharing yuan mode [structural mode]

Mountain wind 2022-06-24 08:02:45 阅读数:874


1. Definition

English name is :Flyweight pattern.

A Flyweight pattern is an object that minimizes memory usage by sharing as much data as possible with other similar objects.

That is, using sharing technology to effectively support the reuse of a large number of fine-grained objects . It greatly reduces the number of objects that need to be created by sharing existing objects 、 Avoid the overhead of a large number of similar objects , So as to improve the utilization rate of system resources .

2. structure

There are two states in the sharing mode :

  1. Internal state , That is, sharable parts that will not change with the change of the environment .
  2. External state , It refers to the unshareable parts that change with the change of the environment . The implementation of the meta sharing mode is to distinguish these two states in the application , And externalize the external state .

3. Role of Xiangyuan

  • Abstract meta roles : It is usually an interface or an abstract class , In the abstract sharing metaclass, it declares the public methods of the concrete sharing metaclass , These methods can provide the internal data of the sharing object to the outside world ( Internal state ), At the same time, these methods can be used to set external data ( External state ).
  • Specific enjoy yuan role : Implement Abstract metaclasses , It's called a meta object ; It provides storage space for the internal state in the specific primitive class . Usually we can combine The singleton pattern To design specific meta classes , Provide a unique meta object for each specific meta class .
  • Non shareable role : Subclasses that cannot be shared can be designed as non shared concrete metaclasses ; When you need an object that does not share a concrete metaclass , Can be created directly by instantiation .
  • Enjoy the role of Yuan factory : Responsible for creating and managing the shareware roles . When a client object requests a sharing object , The shareware factory checks whether there are qualified shareware objects in the system , If it exists, provide it to the customer ; If it doesn't exist , Create a new share object .

4. Case study

【 tetris 】 There are many ways in Tetris , If you create a new object for each square every time you use it , It takes up a lot of space , In this case, we can use the shared meta model to optimize .
 Insert picture description here
among :BoxFactory Is a class of singleton pattern ,Client Get the same every time box Both save memory space for the same object .
Code :

abstract class AbstractBox{

public abstract String getShape();
public void display(String color){

System.out.println("box shape: " + this.getShape() + "color: " + color);
class CBox extends AbstractBox {

public String getShape() {

return "C";
import java.util.HashMap;
class BoxFactory{

private static HashMap<String, AbstractBox> map;
public BoxFactory() {

map = new HashMap<>();
map.put("I", new IBox());
map.put("C", new CBox());
map.put("L", new LBox());
public static final BoxFactory getInstance(){

return SingletonHolder.INSTANCE;
public static class SingletonHolder{

private static final BoxFactory INSTANCE = new BoxFactory();
public AbstractBox getBox(String key){

return map.get(key);
public class Client {

public static void main(String[] args) {

// Get the metadata sharing object through the metadata sharing factory 
AbstractBox cbox1 = BoxFactory.getInstance().getBox("C");
AbstractBox cbox2 = BoxFactory.getInstance().getBox("C");
// Get the same object , Space saved 
System.out.println(cbox1 == cbox2); // TRUE

5. Advantages and disadvantages and use scenarios

advantage :

  1. Reduce the number of similar or identical objects in memory , Save system resources , Improve system performance .
  2. The external state in the meta mode is relatively independent , And does not affect the internal state .

shortcoming :
To make objects share , You need to externalize part of the state of the meta object , Separate into internal state and external state , Complicate the program logic .

Use scenarios :

  1. When a system has a large number of the same or similar objects , Cause a lot of memory consumption .
  2. Most of the state of an object can be externalized , You can pass these external states into the object .
  3. When using the sharing mode, you need to maintain a sharing pool for storing sharing objects , It requires a certain amount of system resources , therefore , It should be worth using the meta sharing mode when you need to read and use the meta sharing object many times .

6.JAVA Real use cases in

  1. stay JDK in Boolean、Byte、Short、Integer、Long、Character And so on packaging class has provided valueOf() Method .
    Long Of valueOf() Method caches -128–127 Between Long object , Objects are reused in this scope , Greater than this range , To create a new Long object ,Integer It's the same .
// A simple test :
class test{

public static void main(String[] args) {

Integer a = -128;
Integer b = -128;
System.out.println(a == b); // true
Integer c = 9000;
Integer d = 9000;
System.out.println(c == d); // false
  1. in addition , When connecting to the database , Connection pool used , It also belongs to an implementation of the meta sharing mode .
  2. The string pool can also be regarded as the embodiment of the yuan sharing mode .
  3. wait .
copyright:author[Mountain wind],Please bring the original link to reprint, thank you.