Skip to content

享元(Flyweight)模式 结构型模式

更新: 2023-05-24 11:11:27   字数: 0 字   时长: 0 分钟

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

c#
// 享元模式示例
using System;
using System.Collections.Generic;

namespace FlyweightPattern
{
    // 享元工厂类
    public class FlyweightFactory
    {
        private Dictionary<string, Flyweight> flyweights = new Dictionary<string, Flyweight>();

        // 获取享元对象
        public Flyweight GetFlyweight(string key)
        {
            Flyweight flyweight;
            if (flyweights.ContainsKey(key))
            {
                flyweight = flyweights[key];
            }
            else
            {
                flyweight = new ConcreteFlyweight(key);
                flyweights.Add(key, flyweight);
            }
            return flyweight;
        }
    }

    // 抽象享元类
    public abstract class Flyweight
    {
        public abstract void Operation(int extrinsicState);
    }

    // 具体享元类
    public class ConcreteFlyweight : Flyweight
    {
        private string key;

        public ConcreteFlyweight(string key)
        {
            this.key = key;
            Console.WriteLine("具体享元" + key + "被创建!");
        }

        public override void Operation(int extrinsicState)
        {
            Console.WriteLine("具体享元" + key + "被调用,外部状态为" + extrinsicState + "。");
        }
    }

    // 客户端类
    public class Client
    {
        static void Main(string[] args)
        {
            int extrinsicState = 22;

            FlyweightFactory factory = new FlyweightFactory();

            Flyweight fx = factory.GetFlyweight("X");
            fx.Operation(--extrinsicState);

            Flyweight fy = factory.GetFlyweight("Y");
            fy.Operation(--extrinsicState);

            Flyweight fz = factory.GetFlyweight("Z");
            fz.Operation(--extrinsicState);

            Flyweight uf = new UnsharedConcreteFlyweight();
            uf.Operation(--extrinsicState);

            Console.ReadKey();
        }
    }

    // 不共享的具体享元类
    public class UnsharedConcreteFlyweight : Flyweight
    {
        public override void Operation(int extrinsicState)
        {
            Console.WriteLine("不共享的具体享元被调用,外部状态为" + extrinsicState + "。");
        }
    }
}
你觉得这篇文章怎么样?
  • 0
  • 0
  • 0
  • 0
  • 0
  • 0
评论
  • 按正序
  • 按倒序
  • 按热度