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

运行结果

相关推荐
asdzx673 分钟前
C#:通过模板快速生成 Word 文档
开发语言·c#·word
游乐码5 分钟前
c#StringBuilder
开发语言·c#
CSharp精选营17 分钟前
都是微软亲儿子,WPF凭啥干不掉WinForm?这3个场景说明白了
c#·wpf·跨平台·winform
panzer_maus33 分钟前
工厂模式、代理模式与单例模式的介绍
java·设计模式·代理模式
糟糕好吃14 小时前
AI 全流程解析(LLM / Token / Context / RAG / Prompt / Tool / Skill / Agent)
前端·后端·设计模式
View1213815 小时前
在 .NET 中使用 Moonshot Kimi + AgentFramework:从 SDK 到 Agent 的完整实践
c#·agent·kimi
FlDmr4i2816 小时前
.NET 10 & C# 14 New Features 新增功能介绍-扩展成员Extension Members
开发语言·c#·.net
QJtDK1R5a18 小时前
C# 14 中的新增功能
开发语言·c#
kvo7f2JTy18 小时前
JAVA 设计模式
java·开发语言·设计模式
雨浓YN19 小时前
WebApi 通讯-DeepSeek API调用文档
c#