享元模式(Flyweight)

享元模式

一. 享元模式

1.1 定义

  • 运用共享技术有效的支持大量细粒度的对象.

二. 具体实现

2.1 创建对象接口

    public interface IFlyweight {
        void print();
    }

2.2 创建具体对象

    public class Flyweight implements IFlyweight {
        private String id;
        public Flyweight(String id){
            this.id = id;
        }
        @Override
        public void print() {
            System.out.println("Flyweight.id = " + getId() + " ...");
        }
        public String getId() {
            return id;
        }
    }

2.3 创建工厂

    public class FlyweightFactory {
        private Map<String, IFlyweight> flyweightMap = new HashMap();
        public IFlyweight getFlyweight(String str){
            IFlyweight flyweight = flyweightMap.get(str);
            if(flyweight == null){
                flyweight = new Flyweight(str);
                flyweightMap.put(str, flyweight);
            }
            return  flyweight;
        }
        public int getFlyweightMapSize(){
            return flyweightMap.size();
        }
    }

2.4 调用

    public static void main(String[] args) {
        FlyweightFactory flyweightFactory = new FlyweightFactory();
        IFlyweight flyweight1 = flyweightFactory.getFlyweight("A");
        IFlyweight flyweight2 = flyweightFactory.getFlyweight("B");
        IFlyweight flyweight3 = flyweightFactory.getFlyweight("A");
        flyweight1.print();
        flyweight2.print();
        flyweight3.print();
        System.out.println(flyweightFactory.getFlyweightMapSize());
    }

2.5 输出

    Flyweight.id = A ...
    Flyweight.id = B ...
    Flyweight.id = A ...
    2

三. 优缺点

3.1 优点

  • 减少对象的创建,节省内存.

3.2 缺点

  • 提升了系统的复杂性.

四. 源码

    https://github.com/Seasons20/DisignPattern.git

END

    原文作者:Knowing
    原文地址: https://segmentfault.com/a/1190000015035255
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞