享元模式:運用共享技術有效地支援大量細粒度的對象。
适用場合:如果一個應用程式适用了大量的對象,而大量的這些對象造成了很大的存儲開銷時就應該考慮使用。
首先定義一個IFlyweight接口
public interface IFlyweight {
public void operation(int extrinsicstate);
}
接着定義一個ConcreteFlyweight繼承IFlyweight
public class ConcreteFlyweight implements IFlyweight{
@Override
public void operation(int extrinsicstate) {
System.out.println("具體flyweight:"+extrinsicstate);
}
}
再定義一個UnsharedConcreteFlyweight繼承IFlyweight
public class UnsharedConcreteFlyweight implements IFlyweight{
@Override
public void operation(int extrinsicstate) {
System.out.println("不共享的具體flyweight:"+extrinsicstate);
}
}
然後定義一個FlyweightFactory
public class FlyweightFactory {
Map<String, IFlyweight> flyweights=new HashMap<String,IFlyweight>();
public FlyweightFactory(){
flyweights.put("x", new ConcreteFlyweight());
flyweights.put("y", new ConcreteFlyweight());
flyweights.put("z", new ConcreteFlyweight());
}
public IFlyweight getFlyweight(String key){
return flyweights.get(key);
}
}
用戶端代碼
public static void main(String[] args) {
//享元模式
int extrinsicstate=;
FlyweightFactory factory=new FlyweightFactory();
IFlyweight fx=factory.getFlyweight("x");
fx.operation(--extrinsicstate);
IFlyweight fy=factory.getFlyweight("y");
fy.operation(--extrinsicstate);
IFlyweight fz=factory.getFlyweight("z");
fz.operation(--extrinsicstate);
IFlyweight uf=new UnsharedConcreteFlyweight();
uf.operation(--extrinsicstate);
}