Java design patterns described in (18): Flyweight

This article Source: GitHub · Click here || GitEE · Click here

First, the use scene

Application Code

public class C01_InScene {
    public static void main(String[] args) {
        String c0 = "cicada" ;
        String c1 = "cicada" ;
        System.out.println(c0 == c1); // true
    }
}

String type is to use the Flyweight pattern. String object is final, the object can not be changed once it is created. String constants are constant pool exists in JAVA, JAVA will ensure that only one copy of a string constant in the constant pool where c0 and c1 is a string constant. The result is: true, explain c0 and c1 two references point to the same string constant constant pool "cicada". This design avoids unnecessary consumption of large amounts of resources when you create more than N identical objects produced.

Second, Flyweight

1. Introduction basis

Flyweight is a configuration object model. Flyweight pattern to share ways to efficiently support a large number of fine-grained objects. Commonly used in low-level development system to address the problem of performance of the system. Like the database connection pool, which is to create a good connection object, there is a need in these connected objects are directly used to avoid re-created.

2, illustrates a pattern

Java design patterns described in (18): Flyweight

3, the core role

  • Abstract Flyweight role

It gives an abstract interface to define the specific roles to achieve the method of sharing.

  • Flyweight specific role

Enjoy implement abstract interfaces defined roles out. If there is an internal state, it must provide the storage capacity of the internal state.

  • Flyweight factory role

Responsible for creating and managing Flyweight role. Flyweight must ensure that objects can be selectively sharing system. When a client calls a target object Flyweight time, if there is already a target Flyweight Flyweight factory to meet the requirements of the role will check the system. If there has been a direct return to the object; if the system does not target the Flyweight, Flyweight factory should create the role Flyweight object.

4, the state of internal and external

  • It refers to the internal state out of the shared information objects stored in the object inside Flyweight with changes in the environment and does not change.
  • External state refers to a labeled target-dependent, and can change with changes in the environment, not shared state.

5, source code implementation

public class C02_FlyWeight {
    public static void main(String[] args) {
        FlyweightFactory factory = new FlyweightFactory();
        Flyweight fly = factory.factoryMethod('c');
        fly.printState("One");
        fly = factory.factoryMethod('d');
        fly.printState("Two");
        fly = factory.factoryMethod('c');
        fly.printState("San");
        // 调用了三次工厂方法,只创建了两个对象
        factory.poolInfo();
    }
}
/**
 * 抽象享元角色类
 */
interface Flyweight {
    void printState (String state);
}
/**
 * 具体享元角色类
 */
class ConcreteFlyweight implements Flyweight {
    private Character innerState = null;
    public ConcreteFlyweight (Character state){
        this.innerState = state;
    }
    @Override
    public void printState(String state) {
        System.out.println("内部状态:" + this.innerState);
        System.out.println("外部状态:" + state);
    }
}
/**
 * 享元工厂角色类
 */
class FlyweightFactory {
    // 模拟数据池
    private Map<Character,Flyweight> pool = new HashMap<>();
    public Flyweight factoryMethod (Character state){
        //先从缓存中查找对象
        Flyweight fly = pool.get(state);
        if(fly == null){
            fly = new ConcreteFlyweight(state);
            pool.put(state, fly);
        }
        return fly;
    }
    public void poolInfo (){
        System.out.println("数据池:"+pool);
    }
}

Three, JDK scenarios

  • Test block
    public class C03_Integer {
    public static void main(String[] args) {
        Integer c1 = Integer.valueOf(127),c2 = Integer.valueOf(127) ;
        Integer c3 = new Integer(127),c4 = new Integer(127) ;
        boolean flag1 = c1==c2 ,flag2 = c2==c3,flag3 = c3==c4 ;
        // true;false;false
        System.out.println(flag1+";"+flag2+";"+flag3);
        Integer c5 = Integer.valueOf(222),c6=Integer.valueOf(222) ;
        // false
        System.out.println(c5==c6);
    }
    }
  • Source code analysis
    public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
    }

    Here the meaning valueOf method is that if the incoming data (-128) to (127) between the direct return from the cache, or create a new Integer object.

Fourth, the model summary

Flyweight memory repetitive object to solve the problem of waste, when the system has a large number of similar objects, the buffer pool when needed. Has been without creating a new object, you can get from the buffer pool. This can reduce system memory, while increasing efficiency. The classic scenario is the technology pool, String constant pool, database connection pool, pool and so are the Flyweight pattern of application, Flyweight pattern is an important way to achieve cell technology. Flyweight makes the system more complicated. In order to make the object can be shared, the time management needs to change the state of the object, which makes the logic becomes complicated.

Fifth, the source code address

GitHub·地址
https://github.com/cicadasmile/model-arithmetic-parent
GitEE·地址
https://gitee.com/cicadasmile/model-arithmetic-parent

Java design patterns described in (18): Flyweight

Guess you like

Origin blog.51cto.com/14439672/2450116