享元模式:就是提前的申请资源备用,当多个地方要重复使用这个实例是就直接拿出来用,而不是从新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);
}

 

 

 

 

 

相关文章:

  • 2021-08-21
  • 2021-08-07
  • 2021-08-01
  • 2021-09-21
  • 2021-11-17
  • 2022-01-22
  • 2021-06-08
  • 2021-12-01
猜你喜欢
  • 2021-09-22
  • 2021-10-19
  • 2022-12-23
  • 2021-10-15
  • 2021-07-18
相关资源
相似解决方案