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

运行结果

相关推荐
回忆2012初秋5 小时前
工厂方法模式完整实现:GPS转换
设计模式·工厂方法模式
xiaoshuaishuai86 小时前
C# GPU算力与管理
开发语言·windows·c#
hez20108 小时前
C# 15 类型系统改进:Union Types
c#·.net·.net core
胡志辉的博客8 小时前
多智能体协作,不是多开几个 Agent:从中介者模式看 OpenClaw 和 Hermes Agent
人工智能·设计模式·ai·agent·中介者模式·openclaw·herman
shark22222229 小时前
能懂!基于Springboot的用户增删查改(三层设计模式)
spring boot·后端·设计模式
FL16238631299 小时前
基于C#winform部署软前景分割DAViD算法的onnx模型实现前景分割
开发语言·算法·c#
C#程序员一枚10 小时前
高可用(High Availability, HA)
数据库·c#
014-code10 小时前
日志规范:怎么写才不算写废话
java·开发语言·设计模式·日志
weixin_5206498710 小时前
C#进阶-特性全知识点总结
开发语言·c#
楼田莉子10 小时前
同步/异步日志系统:日志落地模块\日志器模块\异步日志模块
linux·服务器·c++·学习·设计模式