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

运行结果

相关推荐
大飞pkz17 小时前
【设计模式】题目小练1
开发语言·设计模式·c#·题目小练
lljss202018 小时前
C# 每个chartArea显示最小值、平均值、最大值
开发语言·c#
wearegogog12318 小时前
C#与Twincat 2 实现上位机控制软PLC功能
开发语言·c#
军训猫猫头19 小时前
12.NModbus4在C#上的部署与使用 C#例子 WPF例子
开发语言·c#·wpf
Eiceblue19 小时前
使用 C# 设置 Excel 单元格格式
开发语言·后端·c#·.net·excel
LostXerxes20 小时前
C#的继承和多态
c#
烛阴21 小时前
【TS 设计模式完全指南】TypeScript 装饰器模式的优雅之道
javascript·设计模式·typescript
薄荷撞~可乐1 天前
C#高并发与并行理解处理
开发语言·c#
E___V___E1 天前
设计模式--装饰器模式
python·设计模式·装饰器模式
sali-tec1 天前
C# 基于halcon的视觉工作流-章33-矩状测量
开发语言·人工智能·算法·计算机视觉·c#