享元模式

享元模式

  • 主要是为了节省内存的开支,类似于线程池这样
// 接口
interface FlyWeight {
    public void operation(String s);
}

// 具体实现类
class ConcreteFlyWeight implements FlyWeight {
    private String str;// 内蕴状态

    public ConcreteFlyWeight(String str) {

        this.str = str;
    }

    public void operation(String s) {
        System.out.println("内蕴变量:" + str);
        System.out.println("外蕴变量:" + s);
    }
}

// 享元工厂
class FlyWeightFactory {
    public FlyWeightFactory() {
    }

    private Hashtable<String, ConcreteFlyWeight> flyWeights = new Hashtable<String, ConcreteFlyWeight>();

    public ConcreteFlyWeight factory(String str) {

        ConcreteFlyWeight flyWeight;

        flyWeight = flyWeights.get(str);

        if (null == flyWeight) {
            flyWeight = new ConcreteFlyWeight(str);
            flyWeights.put(str, flyWeight);

        }
        return flyWeight;
    }

    public int getFlyWeightSize() {

        return flyWeights.size();
    }
}

测试类

FlyWeightFactory factory = new FlyWeightFactory();
FlyWeight flyWeight = factory.factory("a");
FlyWeight flyWeight2 = factory.factory("b");
FlyWeight flyWeight3 = factory.factory("a");
flyWeight.operation("a fly weight");
flyWeight2.operation("b fly weight");
flyWeight3.operation("c fly weight");
System.out.println(flyWeight == flyWeight3);
System.out.println(factory.getFlyWeightSize());

本例子享元模式中,享元工厂只有2个对象,外部可以共享他们,并且内蕴变量不会受到影响

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容