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