1.什么是原型模式
2.原型模式有什么优势
3怎么用原型模式
定义:原型模式就是用于创建重复的对象,当想要创建一个新的对象但是开销比较大或者想将对象的当前状态保存下来的时候,我们就可以使用原型模式。
有什么优势:重复创建耗时的对象时,可以明显缩短时间
什么时候用:重复创建耗时的对象.
注意深克隆和浅克隆的区别:
一个对象中的字段有的是值类型的,有的是引用类型的。对于值类型字段来说,它的值就是简单的值,而对于引用类型来说,它的值是地址。
浅复制在复制时,将这个对象的值字段和引用字段(均为非静态字段)全部复制过去,获得了这个对象的值和地址。
即:当其中一个对象的引用字段所指向的地址中的变量变化时,所有浅复制对象中的该引用字段都会发生变化。
深克隆:复制一个现有对象,引用类型指向另一个内存块(改变克隆对象的任何一个值都不会影响其他值)
实现浅克隆:.需要添加一个Clone方法,C#中一般使用MemberwishClone方法来获取实例的浅拷贝副本。
补充:如果想实现深拷贝常用的有两种方法:①将原始实例序列化,然后反序列化赋值给副本对象;②浅拷贝+递归的方式,类似于遍历文件夹,对所有的复杂属性、复杂属性内部的复杂属性都进行浅拷贝。
直接上代码
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading;
namespace prototypeModel
{
//原型模式适用于需要多次初始化,并且初始化耗时的时候
class Program
{
/// <summary>
/// 创建一个抽象类
/// </summary>
[Serializable]
public abstract class prototypeModel
{
public prototypeModel()
{
Thread.Sleep(1000);
}
public prototypeModel(String name, int Id)
{
this.Name = name;
this.Id = Id;
}
public String Name;
public int Id;
public abstract prototypeModel clone();//浅克隆
public abstract prototypeModel Mclone();//深克隆
}
/// <summary>
/// 创建一个类,初始化耗费时间
/// </summary>
[Serializable]
public class prototype : prototypeModel
{
public prototype() : base()
{
}
public prototype(String name, int id) : base(
name, id)
{
}
/// <summary>
/// 二进制流为深克隆
/// </summary>
/// <returns></returns>
public override prototypeModel Mclone()
{
//创建一个内存流
MemoryStream ms = new MemoryStream();
//创建一个二进制序列化对象
BinaryFormatter bf = new BinaryFormatter();
//将当前对象序列化写入ms内存流中
bf.Serialize(ms, this);
//设置流读取的位置
ms.Position = 0;
//将流反序列化为Object对象
return bf.Deserialize(ms) as prototypeModel;
}
/// <summary>
/// 浅克隆
/// </summary>
/// <returns></returns>
public override prototypeModel clone()
{
return this.MemberwiseClone() as prototypeModel;
}
}
static void Main(string[] args)
{
//-------当重复new的是时候耗时3s多
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
prototypeModel prototypeModel = new prototype();
prototypeModel prototypeModel1 = new prototype();
prototypeModel prototypeModel2 = new prototype();
stopwatch.Stop();
Console.WriteLine("耗时:"+stopwatch.Elapsed);
//-------使用原型模式 clone时,耗时1s左右大大降低了时间(浅克隆)
stopwatch.Reset();
stopwatch.Start();
prototypeModel prototypeModel3= new prototype();
prototypeModel prototypeModel4 = prototypeModel3.clone();
prototypeModel prototypeModel5 = prototypeModel3.clone();
stopwatch.Stop();
Console.WriteLine("耗时:" + stopwatch.Elapsed);
//-------使用原型模式 clone时,耗时1s左右大大降低了时间(深克隆)
stopwatch.Reset();
stopwatch.Start();
prototype prototypeModel6 = new prototype();
prototypeModel prototypeModel7 = prototypeModel6.Mclone();
prototypeModel prototypeModel8 = prototypeModel6.Mclone();
stopwatch.Stop();
Console.WriteLine("耗时:" + stopwatch.Elapsed);
}
}
}