享元模式

作者: Stephenwish | 来源:发表于2020-07-28 18:01 被阅读0次
    享元模式本质就是池化思想,让对象实现共用,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");
        }
    }
    

    相关文章

      网友评论

        本文标题:享元模式

        本文链接:https://www.haomeiwen.com/subject/ngcqrktx.html