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

运行结果

相关推荐
咖啡八杯13 小时前
GoF设计模式——享元模式
java·spring·设计模式·享元模式
2601_9620725516 小时前
李梦娇常识4600问|题库|打印版
sql·华为od·华为·c#·华为云·.net·harmonyos
想吃火锅100517 小时前
【前端手撕】instanceof
前端·javascript·原型模式
:mnong17 小时前
学习创建结构行为设计模式
设计模式
m0_5474866618 小时前
《C#语言程序设计与实践》 全套PPT课件
c语言·c#·c语言程序设计
UXbot19 小时前
帮助企业低门槛开展AI应用开发的平台推荐
前端·低代码·ui·交互·产品经理·原型模式·web app
叶帆19 小时前
【YFIOs】用C#开发硬件之设备上云
开发语言·unity·c#
w_t_y_y19 小时前
Agent设计模式(四)多模态融合模式(Multi-Modal Fusion)
设计模式
IT方大同20 小时前
(嵌入式操作系统)信号量
嵌入式硬件·c#
z落落20 小时前
C# FileStream文件流读取文件
开发语言·c#