• 设计模式之享元模式


    享元模式:

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

    示例代码:

    • Flyweight类,它是所有具体享元类的超类或接口,通过这个接口,Flyweight可以接受并作用于外部状态。
    abstract class Flyweight {
        public abstract void Operation(int extrinsicstate);
    }
    
    • ConcreteFlyweight是继承Flyweight超类或实现Flyweight接口,并为内部状态增加存储空间。
    class ConcreteFlyweight : Flyweight {
        public override void Operation(int extrinsicstate) {
            Console.WriteLine("具体Flyweight:" + extrinsicstate);
        }
    }
    
    • UnsharedConcreteFlyweight是指那些不需要共享的Flyweight子类。因为Flyweight接口共享成为可能,但它并不强制共享。
    class UnsharedConcreteFlyweight : Flyweight {
        public override void Operation(int extrinsicstate) {
            Console.WriteLine("不共享的具体Flyweight:" + extrinsicstate);
        }
    }
    
    • FlyweightFactory,是一个享元工厂,用来创建并管理Flyweight对象。它主要是用来确保合理地共享Flyweight,当用户请求一个Flyweight时,FlyweightFactory对象提供一个已创建的实例或者创建一个( 如果不存在的话)。
    class FlyweightFactory {
        private Hashtable flyweights = new Hashtable();
        
        //初始化工厂时,先生成三个实例
        public FlyweightFactory() {
            flyweights.Add("X", new ConcreteFlyweight());
            flyweights.Add("Y", new ConcreteFlyweight());
            flyweights.Add("Z", new ConcreteFlyweight());
        }
        
        //根据客户端请求,获得已生成的实例
        public Flyweight GetFlyweight(String key) {
            return ((Flyweight) flyweights[key]);
        }
    }
    
    • 客户端代码
    static void Main(String[] args) {
        //代码外部状态
        int extrinsicstate = 22;
        
        FlyweightFactory f = new FlyweightFactory();
        
        Flyweight fx = f.GetFlyweight("X");
        fx.Operation(--extrinsicstate);
        
        Flyweight fy = f.GetFlyweight("y");
        fy.Operation(--extrinsicstate);
        
        Flyweight fz = f.GetFlyweight("z");
        fy.Operation(--extrinsicstate);
        
        Flyweight uf = new UnsharedConcreteFlyweight();
        
        uf.Operation(--extrinsicstate);
        
        Console.Read();
    }
    

    结果表示

    具体Flyweight:21
    具体Flyweight:20
    具体Flyweight:19
    不共享的具体Flyweight:18
    
  • 相关阅读:
    除adsense外适合英文站的国外广告联盟(4/12/2011更新)
    盛大云和阿里云之云主机初体验
    【行文格式】
    在线PDF阅读&编辑网站一览
    做销售不得不看的20部电影
    VS中的Code Snippet来提高开发效率
    10个免费的javascript富文本编辑器(jQuery and nonjQuery)
    【操作命令】
    SQLServer常见查询问题
    代码検索
  • 原文地址:https://www.cnblogs.com/sanjun/p/8370919.html
Copyright © 2020-2023  润新知