Flyweight -Flyweight Pattern

When too many objects generated by a software system at run-time, will lead to high running costs, bringing the system performance degradation and other issues. For example there are many repeating characters in a text string, if each character with a separate object to represent, will take up more memory space, then how are we going to avoid a lot of the same or similar objects present in the system, without affecting client programs operate on these objects through an object-oriented way? Flyweight pattern to solve this kind of problem being born. Flyweight achieve the same or similar objects reuse by sharing technology, characters appearing on each of a corresponding logical objects has, however, they do share the same physical element a shared object that can appear in a character strings of different places, the same reference characters refer to the same object instance, in Flyweight mode, examples of these shared objects stored in the local pool is referred Flyweight (Flyweight pool). We can create a different character for each enjoy a meta-object, put it in the pool Flyweight, Flyweight then removed from the pool as needed.

Enjoy the characteristics defined in the meta-schema

Defined Flyweight (Flyweight) mode: Use sharing to support effective reuse a lot of fine-grained objects. It is by sharing existing and rubber to drastically reduce the number of objects that need to be created to avoid a large number of similar kind of overhead, thereby improving the utilization of system resources.

The main advantage Flyweight pattern is: the same as long as the object to save a copy, which reduces the number of objects in the system, thereby reducing the pressure in the system memory to bring fine-grained objects.

The main disadvantages are:

  1. In order to make the object can be shared need not be some of the external shared state, which will increase the complexity of the program.
  2. Flyweight reading external status such that the running time is slightly longer.

Architecture and Implementation of Flyweight

Flyweight following two states mode:

  1. Internal state, that portion will not be shared with the changes in the environment is changed;
  2. External state refers to changes in the environment changes not share a portion. Shared application achieved is to distinguish between the essentials of these two states meta-schema, and external state of the external. To analyze the following basic structure and implementation.

1. Structure Model

The main role Flyweight pattern are as follows.

  1. Abstract character Flyweight (Flyweight): Flyweight all the concrete base class, concrete Flyweight need to implement a common interface specification, non Flyweight external states in the form of parameters passed by the method.
  2. Specific Flyweight (Concrete Flyweight) Role: The abstract interface to enjoy roles as specified.
  3. Non Flyweight (Unsharable Flyweight) Cast: external state is not shared, it injects DETAILED Flyweight correlation in the form of parameters.
  4. Flyweight factory (Flyweight Factory) Role: responsible for creating and managing Flyweight role. When a client requests an object Flyweight objects, whether there Flyweight Flyweight factory inspection system to meet the requirements of the object, if there is available to customers; if it does not exist, create a new Flyweight objects.


FIG 1 is a configuration diagram of Flyweight. FIG. UnsharedConcreteFlyweight is Chun roles, which contains a non-shared external state information info; and Flyweight abstract Flyweight role, which contains Flyweight method of operation (UnsharedConcreteFlyweight state), the non-Flyweight external state parameter form passed by this method; ConcreteFlyweight specific Flyweight role, contains the keyword key, which implements the abstract Flyweight interfaces; FlyweightFactory Flyweight factory is the role that death keyword key to manage specific Flyweight; customer role by sharing yuan factory for specific Flyweight and Flyweight access to related methods of concrete.
 

Flyweight structure of FIG.
FIG 1 is a configuration diagram Flyweight

2. Mode of realization

Flyweight pattern codes are as follows:

package flyweight;
import java.util.HashMap;
public class FlyweightPattern
{
    public static void main(String[] args)
    {
        FlyweightFactory factory=new FlyweightFactory();
        Flyweight f01=factory.getFlyweight("a");
        Flyweight f02=factory.getFlyweight("a");
        Flyweight f03=factory.getFlyweight("a");
        Flyweight f11=factory.getFlyweight("b");
        Flyweight f12=factory.getFlyweight("b");       
        f01.operation(new UnsharedConcreteFlyweight("第1次调用a。"));       
        f02.operation(new UnsharedConcreteFlyweight("第2次调用a。"));       
        f03.operation(new UnsharedConcreteFlyweight("第3次调用a。"));       
        f11.operation(new UnsharedConcreteFlyweight("第1次调用b。"));       
        f12.operation(new UnsharedConcreteFlyweight("第2次调用b。"));
    }
}
//非享元角色
class UnsharedConcreteFlyweight
{
    private String info;
    UnsharedConcreteFlyweight(String info)
    {
        this.info=info;
    }
    public String getInfo()
    {
        return info;
    }
    public void setInfo(String info)
    {
        this.info=info;
    }
}
//抽象享元角色
interface Flyweight
{
    public void operation(UnsharedConcreteFlyweight state);
}
//具体享元角色
class ConcreteFlyweight implements Flyweight
{
    private String key;
    ConcreteFlyweight(String key)
    {
        this.key=key;
        System.out.println("具体享元"+key+"被创建!");
    }
    public void operation(UnsharedConcreteFlyweight outState)
    {
        System.out.print("具体享元"+key+"被调用,");
        System.out.println("非享元信息是:"+outState.getInfo());
    }
}
//享元工厂角色
class FlyweightFactory
{
    private HashMap<String, Flyweight> flyweights=new HashMap<String, Flyweight>();
    public Flyweight getFlyweight(String key)
    {
        Flyweight flyweight=(Flyweight)flyweights.get(key);
        if(flyweight!=null)
        {
            System.out.println("具体享元"+key+"已经存在,被成功获取!");
        }
        else
        {
            flyweight=new ConcreteFlyweight(key);
            flyweights.put(key, flyweight);
        }
        return flyweight;
    }
}


Program results are as follows:

Flyweight a specific created! 
Flyweight a specific existing, successfully get! 
Flyweight a specific existing, successfully get! 
Specific Flyweight b is created! 
Specific Flyweight b already exists, successfully get! 
Flyweight be called a specific, non-Flyweight message is: 1st call a. 
Flyweight be called a specific, non-Flyweight information: 2nd call a. 
Flyweight be called a specific, non-Flyweight information: 3rd call a. 
B is called the specific Flyweight, Flyweight information is non-: 1st call b. 
B is called the specific Flyweight, Flyweight information is non-: 2nd call b.

Examples of meta-schema shared application

[Application Example 1] Flyweight in backgammon game.

Analysis: go with the 331, comprising a plurality of "black" or "white" color pieces, so use Flyweight better.

In this example pieces (ChessPieces) class is abstract Flyweight role, it contains a Lazi DownPieces (Graphics g, Point pt) method; albino (WhitePieces) and sunspots (BlackPieces) class is a concrete Flyweight role, it implements Zi method; Point non Flyweight role, which specifies the location Lazi; WeiqiFactory is Flyweight factory role, to manage pieces through the ArrayList, and provides the acquired albino or sunspots getChessPieces (String type) method; customer category (Chessboard) Graphics board assembly utilizing a draw frame form, and to achieve mouseClicked (MouseEvent e) an event processing method, the method to obtain the white sub Flyweight sunspots or plant according to a user selection and onto the board. Figure 2 is a structural view.
 

Structure Figure backgammon game
FIG 2 is a configuration diagram backgammon game


Code is as follows:

package flyweight;
import java.util.HashMap;
public class FlyweightPattern
{
    public static void main(String[] args)
    {
        FlyweightFactory factory=new FlyweightFactory();
        Flyweight f01=factory.getFlyweight("a");
        Flyweight f02=factory.getFlyweight("a");
        Flyweight f03=factory.getFlyweight("a");
        Flyweight f11=factory.getFlyweight("b");
        Flyweight f12=factory.getFlyweight("b");       
        f01.operation(new UnsharedConcreteFlyweight("第1次调用a。"));       
        f02.operation(new UnsharedConcreteFlyweight("第2次调用a。"));       
        f03.operation(new UnsharedConcreteFlyweight("第3次调用a。"));       
        f11.operation(new UnsharedConcreteFlyweight("第1次调用b。"));       
        f12.operation(new UnsharedConcreteFlyweight("第2次调用b。"));
    }
}
//非享元角色
class UnsharedConcreteFlyweight
{
    private String info;
    UnsharedConcreteFlyweight(String info)
    {
        this.info=info;
    }
    public String getInfo()
    {
        return info;
    }
    public void setInfo(String info)
    {
        this.info=info;
    }
}
//抽象享元角色
interface Flyweight
{
    public void operation(UnsharedConcreteFlyweight state);
}
//具体享元角色
class ConcreteFlyweight implements Flyweight
{
    private String key;
    ConcreteFlyweight(String key)
    {
        this.key=key;
        System.out.println("具体享元"+key+"被创建!");
    }
    public void operation(UnsharedConcreteFlyweight outState)
    {
        System.out.print("具体享元"+key+"被调用,");
        System.out.println("非享元信息是:"+outState.getInfo());
    }
}
//享元工厂角色
class FlyweightFactory
{
    private HashMap<String, Flyweight> flyweights=new HashMap<String, Flyweight>();
    public Flyweight getFlyweight(String key)
    {
        Flyweight flyweight=(Flyweight)flyweights.get(key);
        if(flyweight!=null)
        {
            System.out.println("具体享元"+key+"已经存在,被成功获取!");
        }
        else
        {
            flyweight=new ConcreteFlyweight(key);
            flyweights.put(key, flyweight);
        }
        return flyweight;
    }
}


Result of the program shown in Figure 3.

Operating results backgammon game
Operating results 3 backgammon game

Enjoy scenarios yuan mode

Previous analysis of the structure and features of Flyweight, it applies the following analysis scenarios. Flyweight pattern is to save memory space by reducing the number of objects in memory, so suitable for the following situations Flyweight.

  1. The same or similar large number of objects exist in the system, these objects spend a lot of memory resources.
  2. Most objects can be grouped according to the internal state and external moieties may be different, so that each group only an internal state storage.
  3. Due to the need for additional maintenance Flyweight Flyweight a data structure is stored, so there should be plenty of instances when Flyweight Flyweight worth using.

Flyweight pattern of expansion

In Flyweight pattern described earlier, the structure of FIG portion typically contains shared and not shared portions. In actual use, sometimes a little change, i.e., the presence of two special Flyweight: simple and complex Flyweight Flyweight, they were below briefly.

(1) simple Flyweight, all of the specific class of this Flyweight Flyweight shared mode are possible, in particular non-shared Flyweight class does not exist, the structure shown in Figure 4.
 

Flyweight simple structure of FIG.
FIG 4 a configuration diagram of a simple Flyweight


(2) Composite Flyweight, some objects Flyweight Flyweight this is simply a combination of some of the objects obtained by Flyweight, Flyweight they are complex objects. While the compound can not be shared Flyweight object itself, but they can be decomposed into simple element object again shared is shared, the structure shown in Figure 5.
 

Flyweight composite structure of FIG.
Figure 5 configuration diagram of a composite Flyweight

Guess you like

Origin blog.csdn.net/yucaixiang/article/details/94394221