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

运行结果

相关推荐
我爱cope5 小时前
【从0开始学设计模式-10| 装饰模式】
java·开发语言·设计模式
rockey6275 小时前
AScript函数体系详解
c#·.net·script·eval·expression·function·动态脚本
sg_knight7 小时前
设计模式实战:责任链模式(Chain of Responsibility)
python·设计模式·责任链模式
Pkmer9 小时前
古法编程: 代理模式
后端·设计模式
Pkmer9 小时前
古法编程: 责任链模式
后端·设计模式
Kel11 小时前
LangChain.js 架构设计深度剖析
人工智能·设计模式·架构
Pkmer12 小时前
古法编程: 装饰器模式
设计模式·全栈
吴可可12313 小时前
C#合并首尾相连多段线实战
算法·c#
钮钴禄·爱因斯晨14 小时前
聚焦操作系统中的PV操作
数据库·算法·系统架构·c#
willhuo15 小时前
# 自动化数据采集技术研究与实现:基于Playwright的抖音网页自动化方案
运维·selenium·c#·自动化·chrome devtools·webview