c# 享元模式

2022/9/10 14:59:07

本文主要是介绍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# 享元模式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程