设计模式研究

享元模式

2020-07-28  本文已影响0人  Stephenwish
享元模式本质就是池化思想,让对象实现共用,java 字符串常量池的实现就是享元模式
第一步,建立抽象类
public abstract class FlyWeight {
    final String name;

    public FlyWeight(String name) {
        this.name = name;
    }

    abstract void doSomthing();
}
实现抽象类
public class ConcreteFlysWeight extends FlyWeight{
    public ConcreteFlysWeight(String name) {
        super(name);
    }

    @Override
    void doSomthing() {

    }
}
抽象类里面放置容器hashmap 装载对象
public class FlyWeightFactory {
    private static Map<String,FlyWeight> pool=new HashMap<>();

    public static FlyWeight getFlyWeight(String key){


        FlyWeight flyWeight = pool.get(key);
        if (flyWeight == null) {
            ConcreteFlysWeight weight = new ConcreteFlysWeight(key);
            pool.put(key, weight);
            System.err.println("往池子里新增对象");
        }else{
            System.err.println("从池子里拿出对象");
        }
        return flyWeight;
    }
}

场景测试类
public class Client {
    public static void main(String[] args) {
        FlyWeightFactory.getFlyWeight("hello");
        FlyWeightFactory.getFlyWeight("hello");
    }
}
上一篇下一篇

猜你喜欢

热点阅读