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

运行结果

相关推荐
yong999011 小时前
C# 实时查看硬件使用率(CPU 内存 硬盘 网络)
开发语言·网络·c#
庞轩px13 小时前
第六篇:Spring用了哪些设计模式?——从单例到代理,拆解框架中的经典设计
java·spring·设计模式·bean·代理模式·aop·单例
神仙别闹13 小时前
基于 C# OpenPGP 的文件管理系统
开发语言·c#
多加点辣也没关系13 小时前
设计模式-工厂方法模式
设计模式·工厂方法模式
海盗123415 小时前
C#在Distinct()中使用IEqualityComparer<T>
开发语言·c#
呼Lu噜17 小时前
基于C#的ASP.NET Core中分析async、await的使用场景
数据库·c#·asp.net
多加点辣也没关系17 小时前
设计模式-建造者模式
设计模式·建造者模式
多加点辣也没关系19 小时前
设计模式-桥接模式
设计模式·桥接模式
少许极端19 小时前
AI修炼记3-RAG
人工智能·ai·原型模式·rag
c++之路19 小时前
原型模式(Prototype Pattern)
原型模式