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

运行结果

相关推荐
亓才孓1 分钟前
[设计模式]单例模式饿汉式写法
单例模式·设计模式
代码丰9 分钟前
设计模式:不再手动 set DTO,采用 Builder 模式
设计模式
ghie909011 分钟前
基于C#实现俄罗斯方块游戏
开发语言·游戏·c#
ccut 第一混27 分钟前
C# 基于 RS485 与设备通讯(以照度计为例子)
c#·rs485
老蒋每日coding1 小时前
AI Agent 设计模式系列(二十一)—— 探索和发现设计模式
人工智能·设计模式
贾修行1 小时前
.NET 全栈开发学习路线:从入门到分布式
c#·.net·wpf·asp.net core·web api·winforms·services
无风听海1 小时前
C# 中的 LinkedList
开发语言·c#
chen_2272 小时前
kanzi节点转换插件
c#·kanzi
PfCoder2 小时前
WinForm真入门(22)---定时器控件System.Windows.Forms.Timer
windows·c#·.net·timer