通知 网站从因情语写改为晴雨,这个网站的模板也从calmlog_ex改为 whimurmur

结构型模式-享元模式

875人浏览 / 0人评论 / | 作者:因情语写  | 分类: 设计模式与算法  | 标签: 设计模式与算法  | 

作者:因情语写

链接:https://www.proprogrammar.com/article/448

声明:请尊重原作者的劳动,如需转载请注明出处


  享元模式是对耗资源的对象创建采取事先创建,再使用的一种方式,持有一组对象,要用时先从这一组对象中寻找,找不到再重新创建,通常结合工厂模式创建对象

  享元对象区分了内部状态(Intrinsic State)外部状态(Extrinsic State)

  内部状态是存储在享元对象内部并且不会随环境改变而改变的状态,内部状态可以共享

  外部状态是随环境改变而改变的、不可以共享的状态

package constructional.pattern.flyweight;

public abstract class Flyweight
{
    public abstract void operation();
}
package constructional.pattern.flyweight;

public class ConcreteFlyweight extends Flyweight{
    private String string;
    public ConcreteFlyweight(String str){
    string = str;
    }
    public void operation()
    {
      System.out.println("Concrete---Flyweight : " + string);
    }
}
package constructional.pattern.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
    }

    public int getFlyweightSize() {
        return flyweights.size();
    }
}

  测试代码

package constructional.pattern.flyweight;

public class FlyweightPattern {
    FlyweightFactory factory = new FlyweightFactory();
    Flyweight fly1;
    Flyweight fly2;
    Flyweight fly3;
    Flyweight fly4;
    Flyweight fly5;
    Flyweight fly6;

    /** */
    /** Creates a new instance of FlyweightPattern */
    public FlyweightPattern() {
        fly1 = factory.getFlyWeight("Google");
        fly2 = factory.getFlyWeight("Qutr");
        fly3 = factory.getFlyWeight("Google");
        fly4 = factory.getFlyWeight("Google");
        fly5 = factory.getFlyWeight("Google");
        fly6 = factory.getFlyWeight("Google");
    }

    public void showFlyweight() {
        fly1.operation();
        fly2.operation();
        fly3.operation();
        fly4.operation();
        fly5.operation();
        fly6.operation();
        int objSize = factory.getFlyweightSize();
        System.out.println("objSize = " + objSize);
    }

    public static void main(String[] args) {
        System.out.println("The FlyWeight Pattern!");
        FlyweightPattern fp = new FlyweightPattern();
        fp.showFlyweight();
    }
}

  运行结果


亲爱的读者:有时间可以点赞评论一下

点赞(0) 打赏

全部评论

还没有评论!
广告位-帮帮忙点下广告