Java 之享元模式

 

public interface Flyweight {
    public void operation(String state);
}


public class ConcreteFlyweight implements Flyweight {
    private Character intrinsicState = null;

    /**
     * 構造函數,內蘊狀態做爲參數傳入
     * 
     * @param state
     */
    public ConcreteFlyweight(Character state) {
        this.intrinsicState = state;
    }

    /**
     * 外蘊狀態做爲參數傳入方法中,改變方法的行爲, 可是並不改變對象的內蘊狀態。
     */
    @Override
    public void operation(String state) {
        // TODO Auto-generated method stub
        System.out.println("Intrinsic State = " + this.intrinsicState);
        System.out.println("Extrinsic State = " + state);
    }

}

public class FlyweightFactory {
    private Map<Character, Flyweight> files = new HashMap<Character, Flyweight>();

    public Flyweight factory(Character state) {
        // 先從緩存中查找對象
        Flyweight fly = files.get(state);
        if (fly == null) {
            // 若是對象不存在則建立一個新的Flyweight對象
            fly = new ConcreteFlyweight(state);
            // 把這個新的Flyweight對象添加到緩存中
            files.put(state, fly);
        }
        return fly;
    }
}

public class Client {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        FlyweightFactory factory = new FlyweightFactory();
        Flyweight fly = factory.factory(new Character('a'));
        fly.operation("First Call");

        fly = factory.factory(new Character('b'));
        fly.operation("Second Call");

        fly = factory.factory(new Character('a'));
        fly.operation("Third Call");
    }
}

學習設計模式強烈推薦的博客:java_my_lifejava

代碼地址:lennongit

相關文章
相關標籤/搜索