Java教程

设计模式之享元模式

本文主要是介绍设计模式之享元模式,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

享元模式

  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. 总结:

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

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

这篇关于设计模式之享元模式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!