• 设计模式——享元模式


    Flyweight 直译为蝇量。就其表示的模式来说,翻译成享元,确实是不错的

    package designpattern.structure.flyweight;
    
    public interface Flyweight {
    
        void action(int arg);
    }
    
    package designpattern.structure.flyweight;
    
    public class FlyweightImpl implements Flyweight {
    
        public void action(int arg) {
            // TODO Auto-generated method stub
            System.out.println("FlyweightImpl.action()");
        }
    
    }
    
    
    package designpattern.structure.flyweight;
    
    import java.util.HashMap;
    import java.util.Map;
    
    public class FlyweightFactory {
    
        private static Map<String,Flyweight> flyweights = new HashMap<String,Flyweight>();
           
        public FlyweightFactory(String arg) {
            flyweights.put(arg, new FlyweightImpl());
        }
       
        public static Flyweight getFlyweight(String key) {
            if (flyweights.get(key) == null) {
                flyweights.put(key, new FlyweightImpl());
            }
            return flyweights.get(key);
        }
    
        public static int getSize() {
            return flyweights.size();
        }
    }
    
    
    package designpattern.structure.flyweight;
    
    public class Client {
    
        /**
         * 
         * Fly微Weight量模式 —— 将小对象缓存起来的艺术。、、
         * 
         */
        public static void main(String[] args) {
            Flyweight fly1 = FlyweightFactory.getFlyweight("a");
            fly1.action(1);
           
            Flyweight fly2 = FlyweightFactory.getFlyweight("a");
            System.out.println(fly1 == fly2);
           
            Flyweight fly3 =FlyweightFactory.getFlyweight("b");
            fly3.action(2);
           
            Flyweight fly4 = FlyweightFactory.getFlyweight("c");
            fly4.action(3);
           
            Flyweight fly5 =FlyweightFactory.getFlyweight("d");
            fly4.action(4);
           
            System.out.println(FlyweightFactory.getSize());
        }
    
    }

    总结:

    1 主要就是两个角色:a: 元或者说pojo角色—— 主要属性是其内部状态; b: 工厂角色,用来获取‘元’ 

    2 ‘享’ 的具体实现是—— 工厂获取‘元’的时候,如果已经已经创建过,则直接取出返回;如果没,则创建并加入缓存,再返回

  • 相关阅读:
    Add a column in table control
    ALV
    ABAP Object Differences
    Field Symbols, Casting Decimal Places
    fROM PPV report
    python全局变量
    管理商品demo
    Mac系统在Pycharm中切换解释器
    python中 元组
    python中字符串格式化
  • 原文地址:https://www.cnblogs.com/FlyAway2013/p/3917177.html
Copyright © 2020-2023  润新知