GOF
解釋一下概念
在Flyweight模式中
先定義一個抽象的Flyweight類
public abstract class Flyweight
{
public abstract void operation();
}
在實現一個具體類
public class ConcreteFlyweight extends Flyweight
{
private String string;
public ConcreteFlyweight(String str)
{
string = str;
}
public void operation()
{
System
}
}
實現一個工廠方法類
public class FlyweightFactory
{
private Hashtable flyweights = new Hashtable();
public FlyweightFactory(){}
public Flyweight getFlyWeight(Object obj)
{
Flyweight flyweight = (Flyweight) flyweights
if(flyweight == null)
//產生新的ConcreteFlyweight
flyweight = new ConcreteFlyweight((String)obj);
flyweights
}
return flyweight;
}
public int getFlyweightSize()
{
return flyweights
}
}
最後看看Flyweight的調用
public class FlyweightPattern {
FlyweightFactory factory = new FlyweightFactory();
Flyweight fly
Flyweight fly
Flyweight fly
Flyweight fly
Flyweight fly
Flyweight fly
/** *//** Creates a new instance of FlyweightPattern */
public FlyweightPattern() {
fly
fly
fly
fly
fly
fly
}
public void showFlyweight()
{
fly
fly
fly
fly
fly
fly
int objSize = factory
System
}
public static void main(String[] args)
{
System
FlyweightPattern fp = new FlyweightPattern();
fp
}
}
下面是運行結果
Concrete
Concrete
Concrete
Concrete
Concrete
Concrete
objSize =
我們定義了
From:http://tw.wingwit.com/Article/program/Java/gj/201311/27378.html