关于C# 设计模式 Flyweight 享元模式

关于C# 设计模式 Flyweight 享元模式

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

///Flyweight(享元)模式采用共享来避免大量拥有相同内容对象的开销。
///add by jzh 2007-04-24
namespace DesignPattern
{
    /// <summary>
    /// 享元工厂(FlyweightFactory)角色:本角色负责创建和管理享元角色。
    /// 本角色必须保证享元对象可以被系统适当地共享。
    /// 当一个客户端对象调用一个享元对象的时候,
    /// 享元工厂角色会检查系统中是否已经有一个复合要求的享元对象。
    /// 如果已经有了,享元工厂角色就应当提供这个已有的享元对象;
    /// 如果系统中没有一个适当的享元对象的话,
    /// 享元工厂角色就应当创建一个合适的享元对象。
    /// </summary>
    class FlyweightFactory
    {
        private ArrayList pool = new ArrayList();

        // the flyweightfactory can crete all entries in the pool at startup 
        // (if the pool is small, and it is likely all will be used), or as 
        // needed, if the pool si large and it is likely some will never be used
        public FlyweightFactory()
        {
            pool.Add(new ConcreteEvenFlyweight());
            pool.Add(new ConcreteUnevenFlyweight());
        }

        public Flyweight GetFlyweight(int key)
        {
            int i = key % 2;
            return ((Flyweight)pool[i]);
        }
    }

    /// <summary>
    /// 抽象享元(Flyweight)角色:此角色是所有的具体享元类的超类,
    /// 为这些类规定出需要实现的公共接口,
    /// 通过这个接口Flyweight可以接受并作用于外部状态(Extrinsic State)。
    /// </summary>
    abstract class Flyweight
    {
        abstract public void DoOperation(int extrinsicState);
    }

    /// <summary>
    /// 具体享元(ConcreteFlyweight)角色:实现抽象享元角色所规定的接口。
    /// 如果有内蕴状态(Intrinsic State)的话,
    /// 必须负责为内蕴状态提供存储空间。
    /// 享元对象的内蕴状态必须与对象所处的周围环境无关,
    /// 从而使得享元对象可以在系统内共享的。
    /// </summary>
    class UnsharedConcreteFlyweight : Flyweight
    {
        override public void DoOperation(int extrinsicState)
        {

        }
    }

    class ConcreteEvenFlyweight : Flyweight
    {
        override public void DoOperation(int extrinsicState)
        {
            Console.WriteLine("In ConcreteEvenFlyweight.DoOperation: {0}", extrinsicState);
        }
    }

    class ConcreteUnevenFlyweight : Flyweight
    {
        override public void DoOperation(int extrinsicState)
        {
            Console.WriteLine("In ConcreteUnevenFlyweight.DoOperation: {0}", extrinsicState);
        }
    }

    public class Client
    {
        public static void Main(string[] args)
        {
            int[] data = { 1, 2, 3, 4, 5, 6, 7, 8 };

            FlyweightFactory f = new FlyweightFactory();

            int extrinsicState = 3;
            foreach (int i in data)
            {
                Flyweight flyweight = f.GetFlyweight(i);
                flyweight.DoOperation(extrinsicState);
            }

            Console.ReadLine();
        }
    }
}

 

发表回复

您的电子邮箱地址不会被公开。