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

运行结果

相关推荐
啊QQQQQ2 小时前
设计模式-原型模式
java·设计模式·原型模式
xiaowu0803 小时前
C#设计模式-状态模式
设计模式·c#·状态模式
编程侦探3 小时前
【设计模式】适配器模式:让不兼容的接口和谐共处
开发语言·c++·设计模式·适配器模式
骊山道童4 小时前
设计模式-桥接模式
设计模式·桥接模式
程序员JerrySUN4 小时前
设计模式每日硬核训练 Day 12:装饰器模式(Decorator Pattern)完整讲解与实战应用
设计模式·装饰器模式
朝花惜时4 小时前
物流网络规划-让AI用线性规划方式求解
设计模式·数据挖掘·数据可视化
听闻风很好吃5 小时前
Java设计模式之观察者模式:从入门到架构级实践
java·观察者模式·设计模式
风雅颂FYS6 小时前
C# 经纬度坐标的精度及WGS84(谷歌)、GCJ02(高德)、BD09(百度)坐标相互转换(含高精度转换)
百度·c#
胎粉仔6 小时前
Swift —— delegate 设计模式
开发语言·设计模式·swift
姜行运7 小时前
每日算法(双指针算法)(Day 1)
c++·算法·c#