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);
    }
}

  

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/288568.html

(0)
上一篇 2022年9月10日
下一篇 2022年9月10日

相关推荐

发表回复

登录后才能评论