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

运行结果

相关推荐
北京理工大学软件工程10 小时前
C#111
开发语言·c#
z小天才b16 小时前
Java 设计模式完全指南:从入门到精通
java·开发语言·设计模式
kyriewen1116 小时前
Next.js:让你的React应用从“裸奔”到“穿衣服”
开发语言·前端·javascript·react.js·设计模式·ecmascript
雪飞鸿16 小时前
ArrayPoolWrapper简洁、安全的ArrayPool
c#·.net·.net core·原创
海盗123417 小时前
C#上位机开发-S7协议通信
开发语言·c#
FeBaby17 小时前
ReentrantLock 与 synchronized 底层实现对比图解
开发语言·c#
A-Jie-Y18 小时前
JAVA设计模式-工厂方法模式
java·设计模式
A-Jie-Y18 小时前
JAVA设计模式-单例模式
java·设计模式
烟话619 小时前
C# 内存机制详解:值类型、引用类型与 String 的不可变性
java·jvm·c#