享元模式:就是提前的申请资源备用,当多个地方要重复使用这个实例是就直接拿出来用,而不是从新new
当程序多个地方都要用到这个类,而这个类那么就把这个类的参数移出来,重新抽象一个类,就可以省内存了
这个模式往往要大量的重复实例才会用到。
abstract class Flyweight{
public abstract void Operation(int extrinsicstate);
}
class ConcreteFlyweight extends Flyweight{
public void Operation(int extrinsicstate){
System.out.println("具体Flyweight"+extrinsicstate);
}
}
class UnshareConcreteFlyweight extends Flyweight{
public void Operation(int extrinsicstate){
System.out.println("不共享的具体Flyweight:"+extrimsicstate);
}
}
class FlyweightFactory{
private hashMap<Flyweight> flyweights = new hashMap<Flyweight>;
public FlyweightFactory(){
flyweights.add("X",new ConcreteFlyweight());
flyweights.add("Y",new ConcreteFlyweight());
flyweights.add("Z",new ConcreteFlyweight());
}
public Flyweight getFlyweight(String key){
return ((Flyweight)flyweights.get("X"));
}
}
public class Test{
int extrinsicstate = 22;
FlyweightFactory f = new FlyweightFactory();
Flyweight fx = f.GetFlyweight("X");
fx.Operation(--extrinsicstate);
Flyweight fy = f.GetFlyweight("Y");
fx.Operation(--extrinsicstate);
Flyweight fz = f.GetFlyweight("Z");
fx.Operation(--extrinsicstate);
UnsharedConcreteFlyweight uf = new UnsharedConcreteFlyweight();
uf.Operation(--extrinsicstate);
}