设计模式之享元模式

享元模式

  1. 享元模式结构图

  2. 示例代码

    // 抽象享元角色
    public interface Flyweight {
    
        void doSomething();
    }
    
    // 具体享元角色
    public class ConcreteFlyweight implements Flyweight{
    
        private String status;
    
        public ConcreteFlyweight(String status) {
            this.status = status;
        }
    
        @Override
        public void doSomething() {
            System.out.println("开始工作,状态:" + status);
        }
    }
    
    // 享元工厂
    public class FlyweightFactory {
        private Map<String, Flyweight> pool = new HashMap<>();
    
        public Flyweight getFlyweight(String status){
            if (!pool.containsKey(status)){
                System.out.println("新建享元模式对象");
                pool.put(status, new ConcreteFlyweight(status));
            }
            return pool.get(status);
        }
    
        public int getSize(){
            return pool.size();
        }
    }
    
    
    // 测试类
    public class FlyweightTest {
    
        public static void main(String[] args) {
            FlyweightFactory factory = new FlyweightFactory();
            Flyweight f1 = factory.getFlyweight("忙碌");
            Flyweight f2 = factory.getFlyweight("轻松");
            Flyweight f3 = factory.getFlyweight("魔域");
            Flyweight f4 = factory.getFlyweight("忙碌");
            System.out.println(factory.getSize());
        }
    }
    
    
  3. 总结:

    优点:减少了对象的创建,降低了资源的消耗,提供效率;

    缺点:关注内外部状态,关注线程安全问题,使系统逻辑复杂化.

posted @ 2021-04-17 17:07  justKen  阅读(40)  评论(0编辑  收藏  举报