设计模式|享元模式

运用享元模式(Flyweight)可以有效地支持大量细粒度的对象。

类结构

image.png

代码

package com.elltor.designpattern.Flyweight;

public interface Flyweight {
    void operation(int i);
}
package com.elltor.designpattern.Flyweight;

public class ConcreteFlyweight implements Flyweight {

    @Override
    public void operation(int i) {
        System.out.println("具体的享元对象: "+i);
    }
}
package com.elltor.designpattern.Flyweight;

import java.util.HashMap;

public class FlyweightFcatory {
    private HashMap<String,ConcreteFlyweight> flyweightMap = new HashMap<>();

    public FlyweightFcatory() {
        flyweightMap.put("A",new ConcreteFlyweight());
        flyweightMap.put("B",new ConcreteFlyweight());
        flyweightMap.put("C",new ConcreteFlyweight());
        flyweightMap.put("D",new ConcreteFlyweight());
        flyweightMap.put("E",new ConcreteFlyweight());
    }

    public Flyweight getFlyweight(String key){
        return flyweightMap.get(key);
    }
}
package com.elltor.designpattern.Flyweight;

public class UnsharedFlyweight implements Flyweight {
    @Override
    public void operation(int i) {
        System.out.println("不被共享的享元对象: "+i);
    }
}
package com.elltor.designpattern.Flyweight;

public class Main {
    public static void main(String[] args) {
        int i = 100;
        FlyweightFcatory factory = new FlyweightFcatory();

        Flyweight flyweightA = factory.getFlyweight("A");
        flyweightA.operation(i);

        Flyweight flyweightB = factory.getFlyweight("B");
        flyweightB.operation(i*2);

        Flyweight flyweightC = factory.getFlyweight("C");
        flyweightC.operation(i*3);

        Flyweight flyweightD = factory.getFlyweight("D");
        flyweightD.operation(i*4);

        Flyweight flyweightE = factory.getFlyweight("E");
        flyweightE.operation(i*5);
    }

}
//打印结果
具体的享元对象: 100
具体的享元对象: 200
具体的享元对象: 300
具体的享元对象: 400
具体的享元对象: 500

抽离表象, 用同一个对象表示不同"外观"的对象, 这些"外观"的差异是由数据的不同而产生。