责任型模式之FLyweight(享元)模式

1.如果你期望将共享的细粒度对象的责任集中在一个对象,可使用FLyweight(享元)模式
2.举例

//d单元抽象类
public abstract class Flyweight{  
    public abstract void operation();  
}  
//单元具体类
public class WordFlyweight extends Flyweight{
    private String string;
    public WordFlyweight(String string) {
        // TODO Auto-generated constructor stub
        this.string = string;
    }
    @Override
    public void operation() {
        // TODO Auto-generated method stub
        System.out.println("WordFlyweight : " + string); 
    }

}
import java.util.Hashtable;
//享元工厂类:如果存在该对象则直接使用,否则创建新单元类
public class FlyweightFactory {
    private Hashtable flyweights = new Hashtable<>();
    public FlyweightFactory() {
        // TODO Auto-generated constructor stub
    }
    public Flyweight getFlyweight(Object obj) {
        Flyweight flyweight = (Flyweight)flyweights.get(obj);
        if(flyweight==null){
            flyweight = new WordFlyweight((String)obj);
            flyweights.put(obj, flyweight);
        }
        return flyweight;
    }
    public int getFlyweightsSize(){
        return flyweights.size();
    }
}
//测试类
public class Test {
    public static void main(String[] args){
        FlyweightFactory ff = new FlyweightFactory();

        Flyweight f1 = ff.getFlyweight("f1");
        Flyweight f2 = ff.getFlyweight("f2");
        Flyweight f3 = ff.getFlyweight("f1");

        f1.operation();
        f2.operation();
        f3.operation();

        System.out.println(ff.getFlyweightsSize());
    }
}
//结果
WordFlyweight : f1
WordFlyweight : f2
WordFlyweight : f1
2

3.总结:FLyweight(享元)模式的主要意图在于通过共享大量的细粒度对象的使用效率。设置享元类的可见性修饰符可以在某些方面帮助我们控制其他开发者对享元对象的访问,但是内部类可以做得更好(即单元类作为工厂类的内部类),能够确保享元类智能被享元工厂类访问。
4.参考:http://blog.csdn.net/jason0539/article/details/22908915

你可能感兴趣的:(享元模式)