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

运行结果

相关推荐
hhb_6188 小时前
Dylan 语言核心特性与工程实践深度解析
开发语言·c#
CSharp精选营9 小时前
最新.NET新手入门学习网站合集(2026更新版)
c#·学习资料·开发教程·.net 新手入门·开放资源·.net网站
小程故事多_8012 小时前
从Claude Code源码中,拆解13个可直接复用的Agentic Harness设计模式(生产级实战解析)
人工智能·设计模式·智能体·claude code·harness
hhb_61812 小时前
C#高性能异步编程实战与底层原理深度解析
开发语言·c#
beyond谚语13 小时前
反射、特性和依赖注入
c#
Tiger_shl14 小时前
C# 托管对象、非托管对象 讲解
开发语言·c#
LF男男14 小时前
Action- C# 内置的委托类型
java·开发语言·c#
踩着两条虫17 小时前
VTJ 平台六大设计模式落地实战指南
开发语言·前端·人工智能·低代码·设计模式·重构·架构
2501_9307077818 小时前
使用C#代码在 PowerPoint 中创建组合图表
开发语言·c#·powerpoint
石油人单挑所有19 小时前
基于多设计模式下的同步&异步日志系统测试报告
服务器·c++·vscode·设计模式