GOF: The use of shared technology to effectively support a large number of fine-grained objects.
Explain the concept: that is, if you have multiple identical objects in a system, then just share one copy, and you don't have to instantiate an object for each. For example (refer to the example in Gof book) a text system, each letter to set an object, then the large lowercase letter is 52, then you need to define 52 objects. If there is a 1M text, then the letter is so much, if each letter defines an object then memory burst. So if you share an object with each letter, you save a lot of resources.
In flyweight mode, factory patterns often occur in flyweight mode because of the variety of objects to be produced. The internal state of the Flyweight is shared, and Flyweight factory is responsible for maintaining an object storage pool (Flyweight pool) to store the internal state. Flyweight mode is a model that improves program efficiency and performance, and can greatly speed up the running of programs. There are many applications, for example:
First, define an abstract flyweight class:
package Flyweight;
public abstract class Flyweight
...
{
public abstract void operation();
}//end abstract class Flyweight
In implementing a specific class:
package Flyweight;
public class ConcreteFlyweight extends Flyweight
...
{
private String string;
public ConcreteFlyweight(String str)
...
{
string = str;
}//end ConcreteFlyweight(...)
public void operation()
...
{
System.out.println("Concrete---Flyweight : " + string);
}//end operation()
}//end class ConcreteFlyweight
Implement a factory method class:
package Flyweight;
import java.util.Hashtable;
public class FlyweightFactory
...
{
private Hashtable flyweights = new Hashtable();//----------------------------1
public FlyweightFactory() ...{}
public Flyweight getFlyWeight(Object obj)
...
{
Flyweight flyweight = (Flyweight) flyweights.get(obj);//----------------2
if(flyweight == null) ...{//---------------------------------------------------3
//产生新的ConcreteFlyweight
flyweight = new ConcreteFlyweight((String)obj);
flyweights.put(obj, flyweight);//--------------------------------------5
}
return flyweight;//---------------------------------------------------------6
}//end GetFlyWeight(...)
public int getFlyweightSize()
...
{
return flyweights.size();
}
}//end class FlyweightFactory