Flyweight mode

I. definition

Using sharing technology to effectively support a large number of fine-grained objects. Also known as "fly quantity mode".

When it comes to sharing mode, the first thing I think about is pool technology. String constant pool, database connection pool, buffer pool and so on are all applications of sharing mode, so sharing mode is an important implementation of pool technology. For example, each time we create a string object, we need to create a new string object, so the memory overhead will be huge. So if we create the string object "adam" for the first time, and then create the same string "adam" for the next time, we just point its reference to "adam", thus realizing the sharing of "adam" string in memory.

The sharing mode uses a share to avoid the cost of having a large number of the same content objects. The most common and intuitive cost is memory consumption. The key to sharing is to distinguish Internal State from External State.

The internal state is stored in the sharing object and will not change with the change of the environment. Internal state can be shared.

The external state changes with the environment and cannot be shared. The external state of the sharing object must be saved by the client, and after the sharing object is created, it will be transferred into the sharing object when it needs to be used. The external state cannot affect the internal state of the sharing object. They are independent of each other.

Sharing mode can be divided into simple sharing mode and compound sharing mode.

2, Simple sharing mode

The role of simple sharing mode is as follows:

Abstract membership role (Flyweight): an abstract interface is given to specify the implementation methods of all concrete membership roles.

Concrete flyweight: implements the interface specified by the abstract sharerole. If there is an internal state, it must be responsible for providing storage space for the internal state.

Flyweightfactory: this role is responsible for creating and managing (providing a pool container, usually HashMap) the shared role. This role must ensure that the sharing object can be properly shared by the system. When a client object calls a shareware object, the shareware factory role checks whether there is a shareware object that meets the requirements in the system. If it already exists, the sharing factory role should provide the existing sharing object; if there is no appropriate sharing object in the system, the sharing factory role should create an appropriate sharing object.

Abstract sharing role:

package com.wuychn.flyweight.pure;

public interface Flyweight {

    void operation(String state);

}

Specific role:

package com.wuychn.flyweight.pure;

public class ConcreteFlyweight implements Flyweight {

    private String str;

    public ConcreteFlyweight(String str) {
        this.str = str;
    }

    public void operation(String state) {
        System.out.println("Internal status:" + str);
        System.out.println("External status:" + state);
    }
}

Xiangyuan factory role:

package com.wuychn.flyweight.pure;

import java.util.HashMap;
import java.util.Map;

public class FlyWeightFactory {

    private Map<String, ConcreteFlyweight> flyWeights = new HashMap<String, ConcreteFlyweight>();

    public ConcreteFlyweight get(String str) {
        ConcreteFlyweight flyweight = flyWeights.get(str);
        if (flyweight == null) {
            flyweight = new ConcreteFlyweight(str);
            flyWeights.put(str, flyweight);
        }
        return flyweight;
    }

    public int getFlyWeightSize() {
        return flyWeights.size();
    }
}

Test code:

package com.wuychn.flyweight.pure;

public class Test {

    public static void main(String[] args) {
        FlyWeightFactory factory = new FlyWeightFactory();
        Flyweight f1 = factory.get("a");
        Flyweight f2 = factory.get("b");
        Flyweight f3 = factory.get("a");

        f1.operation("a fly weight");
        f2.operation("b fly weight");
        f3.operation("c fly weight");

        System.out.println(f1 == f3);
        System.out.println(factory.getFlyWeightSize());

    }

}

Result:

Internal status: a
 External state: a fly weight
 Internal status: b
 External status: b fly weight
 Internal status: a
 External state: c fly weight
true
2

3, Compound sharing mode

In the simple sharing model, all sharing objects are simple sharing objects, that is to say, they can be shared directly. Some simple sharing objects can be compounded using the composite model to form a composite sharing object. Such composite sharing objects cannot be shared by themselves, but they can be decomposed into simple sharing objects, and the latter can be shared.

The role of composite sharing mode is as follows:

Abstract membership role (Flyweight): an abstract interface is given to specify the implementation methods of all concrete membership roles.

Concrete flyweight: implements the interface specified by the abstract sharerole. If there is an internal state, it must be responsible for providing storage space for the internal state.

Concrete composite flyweight: the object represented by a composite shareweight can not be shared, but a composite shareweight object can be decomposed into a combination of multiple simple shareweight objects. The composite sharing role is also called the sharing object that cannot be shared.

Flyweightfactory: this role is responsible for creating and managing the role. This role must ensure that the sharing object can be properly shared by the system. When a client object calls a shareware object, the shareware factory role checks whether there is a shareware object that meets the requirements in the system. If it already exists, the sharing factory role should provide the existing sharing object; if there is no appropriate sharing object in the system, the sharing factory role should create an appropriate sharing object.

The code of abstract and specific sharing role is the same as that of simple sharing mode.

Composite membership objects are composed of simple membership objects through composition, so an aggregation management method such as add() is provided. Because a composite shareable object has different aggregation elements, which are added after the composite shareable object is created, this means that the state of the composite shareable object will change, so the composite shareable object cannot be shared:

package com.wuychn.flyweight.composite;

import com.wuychn.flyweight.pure.Flyweight;

import java.util.HashMap;
import java.util.Map;

public class ConcreteCompositeFlyweight implements Flyweight {

    private Map<String, Flyweight> flyWeights = new HashMap<String, Flyweight>();

    public void add(String key, Flyweight fly) {
        flyWeights.put(key, fly);
    }

    public void operation(String state) {
        Flyweight fly = null;
        for (String s : flyWeights.keySet()) {
            fly = flyWeights.get(s);
            fly.operation(state);
        }
    }
}

The sharing factory role provides two different methods: one is to provide a simple sharing object, and the other is to provide a composite sharing object:

package com.wuychn.flyweight.composite;

import com.wuychn.flyweight.pure.ConcreteFlyweight;
import com.wuychn.flyweight.pure.Flyweight;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FlyweightCompositeFactory {
    private Map<String, Flyweight> flyWeights = new HashMap<String, Flyweight>();

    public Flyweight get(List<String> compositeStates) {
        ConcreteCompositeFlyweight compositeFly = new ConcreteCompositeFlyweight();
        for (String s : compositeStates) {
            compositeFly.add(s, this.get(s));
        }
        return compositeFly;
    }

    public Flyweight get(String s) {
        Flyweight fly = flyWeights.get(s);
        if (fly == null) {
            fly = new ConcreteFlyweight(s);
            flyWeights.put(s, fly);
        }
        return fly;
    }
}

Test code:

package com.wuychn.flyweight.composite;

import com.wuychn.flyweight.pure.Flyweight;

import java.util.ArrayList;
import java.util.List;

public class Test {

    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        list.add("a");
        list.add("b");
        list.add("c");
        list.add("a");
        list.add("b");

        FlyweightCompositeFactory factory = new FlyweightCompositeFactory();
        Flyweight f1 = factory.get(list);
        Flyweight f2 = factory.get(list);
        f1.operation("Composite Call");
        System.out.println("=======");
        System.out.println("Can composite sharing mode share objects" + (f1 == f2));

        String str = "a";
        Flyweight f3 = factory.get(str);
        Flyweight f4 = factory.get(str);
        System.out.println("Whether the simple sharing mode can share objects:" + (f3 == f4));

    }

}

Operation result:

Internal status: a
 External status: Composite Call
 Internal status: b
 External status: Composite Call
 Internal status: c
 External status: Composite Call
=======
Whether objects can be shared in composite sharing mode: false
 Whether object can be shared in simple sharing mode: true

It can be seen from the above example that the external states of all elements of a compound entity are equal to the external states of the compound entity. In general, the internal state of a simple membership object contained in a composite membership object is not equal. Composite sharing objects cannot be shared. Simple sharing objects can be shared.

4, Advantages and disadvantages

Advantage: dramatically reduces the number of objects in memory.

Disadvantages: the sharing mode makes the system more complex. In order to share objects, some states need to be externalized, which complicates the logic of the program. The sharing mode externalizes the state of the sharing object, while reading the external state makes the running time slightly longer.

Original text: https://www.cnblogs.com/adamjwh/p/9070107.html

100 original articles published, 91 praised, 20000 visitors+
Private letter follow

Tags: Java Database

Posted on Mon, 20 Jan 2020 21:09:42 -0800 by a94060