编程语言
首页 > 编程语言> > c# 享元模式

c# 享元模式

作者:互联网

// See https://aka.ms/new-console-template for more information
/*
 个人理解
工厂内先把对象准备好
然后根据参数去取对象

 */
int val = 10;
XiaoMiFactory miFactory = new();
ImplementationProduct product = miFactory.GetFlyweight("A");
if (product != null) 
{
    product.CreateXiaoMiProduct(val);
}


public  class XiaoMiFactory
{
    private Dictionary<string, object>? dic = new();
    public XiaoMiFactory() 
    {
        dic.Add("A", new ImplementationProduct("小米10"));
        dic.Add("B", new ImplementationProduct("小米9"));
        dic.Add("C", new ImplementationProduct("红米8"));
    }
    public ImplementationProduct GetFlyweight(string key)
    {
        return dic[key] as ImplementationProduct;
    }
}
 

/// <summary>
/// 产品抽象
/// </summary>
public abstract class Product 
{
    public abstract void CreateXiaoMiProduct(int innerState);
}
/// <summary>
/// 实现产品
/// </summary>
public class ImplementationProduct : Product
{
    private string intrinsicstate;
    public ImplementationProduct(string innerState) 
    {
        intrinsicstate = innerState;
    }
    public override void CreateXiaoMiProduct(int extrinsicstate)
    {
        Console.WriteLine("具体实现类: 内部状态 {0}, 外在状态 {1}", intrinsicstate, extrinsicstate);
    }
}

  

标签:享元,c#,innerState,ImplementationProduct,dic,int,模式,new,public
来源: https://www.cnblogs.com/liujian1368928/p/16674027.html