• 设计模式之享元模式


    享元模式

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

    FlyWeight

    package com.hml.flyweight;
    
    public abstract class FlyWeight {
        public abstract void operation(int p);
    }

    ConcreateFlyWeight

    package com.hml.flyweight;
    
    public class ConcreateFlyWeight extends FlyWeight {
    
        @Override
        public void operation(int p) {
            System.out.println("具体的类:" + p);
        }
    
    }

    FlyWeigthFactory

    package com.hml.flyweight;
    
    import java.util.HashMap;
    import java.util.Map;
    
    public class FlyWeigthFactory {
        private static Map<String, FlyWeight> flyweigths = new HashMap<String, FlyWeight>();
    
        static {
            flyweigths.put("x", new ConcreateFlyWeight());
            flyweigths.put("y", new ConcreateFlyWeight());
            flyweigths.put("z", new ConcreateFlyWeight());
        }
    
        public static FlyWeight getFlyWeight(String key) {
            return flyweigths.get(key);
        }
    }

    Test

    package com.hml.flyweight;
    
    public class Test {
        public static void main(String[] args) {
            
            FlyWeigthFactory factory = new FlyWeigthFactory();
            FlyWeight f = factory.getFlyWeight("x");
            f.operation(22);
            f = factory.getFlyWeight("y");
            f.operation(22);
        }
    }

    类图

    享元模式可以避免大量非常相似类的开销。在程序设计中,有时需要生成大量细粒度的类的实例来表示数据。如果能发现这些实例除了几个参数外基本上相同,有时就能够大幅度的减少需要实例化的类的数量。如果能把参数移到类的外面,在方法调用时传递进来,就可以可以通过共享减少单个实例的数据量。

  • 相关阅读:
    NOJ-1581 筷子 (线性DP)
    UVA-242 Stamps and Envelope Size (DP)
    POJ 1860 (SPFA判断正环)
    POJ 3268 最短路水题
    STL----priority_queue
    STL----unique
    POJ 2031(最小生成树Kruskal算法+几何判断)
    POJ 3468(线段树区间修改+区间求和)
    学习线段树
    POJ 1251(最小生成树裸题)
  • 原文地址:https://www.cnblogs.com/heml/p/4656709.html
Copyright © 2020-2023  润新知