【C#设计模式(5)——原型模式(Prototype Pattern)】

前言

C#设计模式(5)------原型模式(Prototype Pattern)

通过复制现在有对象来创造新的对象,简化了创建对象过程。

代码

csharp 复制代码
//原型接口
public interface IPrototype
{
    IPrototype Clone();
}
//文件管理类
public class FileManager: IPrototype
{
    private string fileName;
    public string FileName { get => fileName; set => fileName = value; }
    public FileManager(string fileNmae)
    {
        this.FileName = fileNmae;
    }
    public IPrototype Clone()
    {
        try
        {
            return (IPrototype)this.MemberwiseClone();
        }
        catch (System.Exception ex)
        {
            return null;
        }
    }
}

/*
 * 原型模式:Prototype Pattern
 */
internal class Program
{
    static void Main(string[] args)
    {
        FileManager prototype = new FileManager("新建文件");
        FileManager prototypeCopy = (FileManager)prototype.Clone();

        prototypeCopy.FileName = "新建文件-副本";

        Console.WriteLine($"hash[{prototype.GetHashCode()}],原文件名:{prototype.FileName}");
        Console.WriteLine($"hash[{prototypeCopy.GetHashCode()}],备份文件名:{prototypeCopy.FileName}");

        Console.ReadLine();
    }
}

运行结果

相关推荐
ZJPRENO1 小时前
吃透软件开发六大设计原则,告别烂代码
设计模式
咖啡八杯1 小时前
GoF设计模式——命令模式
java·设计模式·架构
花椒技术17 小时前
HJPusher / HJPlayer SDK 实践:我们为什么把直播推播链路拆成一套可复用能力
设计模式·harmonyos·直播
雨落倾城夏未凉21 小时前
第四章c#方法-参数数组和可选参数(16)
后端·c#
艺艺生辉1 天前
迭代器模式-"我也想被增强for循环"
设计模式
唐青枫2 天前
线程不是越多越快:C#.NET Thread 生命周期、同步与后台工作线程实战
c#·.net
咖啡八杯3 天前
GoF设计模式——策略模式
java·后端·spring·设计模式
唐青枫3 天前
别只会反射:C#.NET Emit 动态生成代码实战详解
c#·.net
咕白m6253 天前
.NET 环境下 Word 超链接批量提取方案
c#·.net