CSharp: Prototype Pattern in donet 6
/// <summary>
/// 原型模式 Prototype Pattern
/// </summary>
public interface IColorPrototype
{
/// <summary>
///
/// </summary>
/// <returns></returns>
IColorPrototype Clone();
}
/// <summary>
/// 原型模式 Prototype Pattern
/// </summary>
public class Color : IColorPrototype
{
/// <summary>
///
/// </summary>
/// <param name="red"></param>
/// <param name="green"></param>
/// <param name="blue"></param>
public Color(int red, int green, int blue)
{
Red = red;
Green = green;
Blue = blue;
}
/// <summary>
///
/// </summary>
public int Red { get; set; }
/// <summary>
///
/// </summary>
public int Green { get; set; }
/// <summary>
///
/// </summary>
public int Blue { get; set; }
/// <summary>
///
/// </summary>
/// <param name="red"></param>
/// <param name="green"></param>
/// <param name="blue"></param>
public void Customize(int red, int green, int blue)
{
Red = red;
Green = green;
Blue = blue;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public IColorPrototype Clone()
{
Console.WriteLine($"\n克隆的颜色 RGB: {Red},{Green},{Blue}");
return (MemberwiseClone() as IColorPrototype)!;
}
}
/// <summary>
/// 原型模式 Prototype Pattern
/// </summary>
public class ColorRegistry
{
/// <summary>
///
/// </summary>
private readonly Dictionary<string, IColorPrototype> _colors = new();
/// <summary>
///
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public IColorPrototype this[string key]
{
get => _colors[key];
set => _colors[key] = value;
}
/// <summary>
///
/// </summary>
public void List()
{
Console.WriteLine("注册表中可用的颜色...");
foreach (var color in _colors)
{
Console.WriteLine($"名称: {color.Key}");
}
}
}
/// <summary>
////原型模式 Prototype Pattern
/// </summary>
public static class ColorRegistryExecutor
{
public static void Execute()
{
ConsoleExtension.WriteSeparator("颜色注册示例 ");
// Initialize registry with standard colors.
var registry = new ColorRegistry
{
["red"] = new Color(255, 0, 0),
["green"] = new Color(0, 255, 0),
["blue"] = new Color(0, 0, 255)
};
registry.List();
// Clone red color and store it in the registry.
var clonedColor = (registry["red"].Clone() as Color)!;
clonedColor.Customize(clonedColor.Red, clonedColor.Green, 33);
registry["custom"] = clonedColor;
registry.List();
// Clone custom color without storing it in the registry.
_ = (registry["custom"].Clone() as Color)!;
registry.List();
}
}
调用:
Geovin.Du.DuPrototype.ColorRegistry.ColorRegistryExecutor.Execute();
颜色注册示例 -------------------------------------------------- 注册表中可用的颜色... 名称: red 名称: green 名称: blue 克隆的颜色 RGB: 255,0,0 注册表中可用的颜色... 名称: red 名称: green 名称: blue 名称: custom 克隆的颜色 RGB: 255,0,33 注册表中可用的颜色... 名称: red 名称: green 名称: blue 名称: custom



图片来源于联想集团2022联想创新科技大会
哲学管理(学)人生, 文学艺术生活, 自动(计算机学)物理(学)工作, 生物(学)化学逆境, 历史(学)测绘(学)时间, 经济(学)数学金钱(理财), 心理(学)医学情绪, 诗词美容情感, 美学建筑(学)家园, 解构建构(分析)整合学习, 智商情商(IQ、EQ)运筹(学)生存.---Geovin Du(涂聚文)
浙公网安备 33010602011771号