享元模式

Posted by Lazy on July 2, 2016

##享元模式

  • 主要是为了节省内存的开支,类似于线程池这样
// 接口
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个对象,外部可以共享他们,并且内蕴变量不会受到影响