C#设计模式之原型(ProtoType)

1. 为什么要用原型?用原型的好处

比如我们有一个工具栏按钮,新建按钮,它是 ToolbarButton 的实例,它有长度、宽度属性等,而且属性都赋了值。

现在我们要再添加一个保存按钮,它也是 ToolbarButton 的实例,它也有长度、宽度属性等,不过它还没赋值,它的值和新建按钮的值一样。

如果我们不用原型设计模式的话,可能重新赋一遍值。如果我们用原型设计模式的话,我们可以把新建按钮作为保存按钮的原型。那样的话就不需要再给保存按钮赋值,它的默认的长度、宽度就和新建按钮一样了。

2. 在 C# 中怎样用原型?

因为类的实例是引用类型,要想用原有的类中的实例的数据的话,只能用 clone 方法。

Clone 方法分为深 clone 和浅 clone

在 C# 中提供了浅 clone 的方法,即为 MemberwiseClone()

C# 浅 Clone 的例子:

using System;

namespace DesignPattern

{

public class ToolbarButton : ICloneable // 实现 Clone 接口

{

private int _Width;

private int _Height;

public ToolbarButton()

{

}

public int Width

{

get

{

return _Width;

}

set

{

_Width= value ;

}

}

public int Height

{

get

{

return _Height;

}

set

{

_Height= value ;

}

}

public object Clone()

{

return this .MemberwiseClone(); // 返回浅 clone 方法 ¨

}

}

public class Test

{

public void TestMethod()

{

ToolbarButton mtb_NewButton= new ToolbarButton();

mtb_NewButton.Width=60;

mtb_NewButton.Height=30;

ToolbarButton mtb_SaveButton= new ToolbarButton();

mtb_SaveButton=(ToolbarButton)mtb_NewButton.Clone();

// 这时 mtb_SaveButton 就有 Width 和 Height 的值了

}

}

}

Published At
Categories with Web编程
Tagged with
comments powered by Disqus