设计模式(享元模式)

享元模式可以理解是一个对象的缓存,通过构建一个享元工厂对所有的对象进行管理。

代码如下:

  • Flyweight 享元的接口
public interface Flyweight {
    public void doAction();
}
  • FlyweightImpl 具体被共享的类实现
public class FlyweightImpl implements Flyweight{

    @Override
    public void doAction() {
        System.out.println("doAction");
    }
}
  • FlyweightFactory 享元工厂
public class FlyweightFactory {

    private static Map<String, Flyweight> flyweights 
        = new HashMap<String, Flyweight>();

    public static Flyweight getFlyweight(String key) {
        if (flyweights.get(key) == null) {
            flyweights.put(key, new FlyweightImpl());
        }
        return (Flyweight) flyweights.get(key);
    }

    public static int getSize() {
        return flyweights.size();
    }
}
  • APP 测试类
public class App {

    public static void main(String[] args) {
        FlyweightFactory factory = new FlyweightFactory();
        factory.getFlyweight("a").doAction();
        factory.getFlyweight("b").doAction();
        factory.getFlyweight("a").doAction();
        
        System.out.println(factory.getSize());
    }
}
  • 输出结果
doAction
doAction
doAction
2

你可能感兴趣的:(设计模式)