C#设计模式之原型(ProtoType)
来源:互联网 发布:家装设计软件app 编辑:程序博客网 时间:2024/06/18 02:35
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的值了
}
}
}
- C#设计模式之原型(ProtoType)
- C#设计模式之原型(ProtoType)
- C#设计模式之原型(ProtoType)
- C#设计模式之原型(ProtoType)
- C# 设计模式之原型模式(Prototype)
- C#设计模式之原型模式(Prototype Pattern)
- 设计模式之Prototype(原型)
- 设计模式之Prototype(原型)
- 设计模式之Prototype(原型)
- 设计模式之Prototype(原型)
- 设计模式之Prototype(原型)
- 设计模式之Prototype(原型)
- 设计模式之Prototype(原型)
- 设计模式之Prototype(原型)
- 设计模式之Prototype(原型)
- 设计模式之Prototype(原型)
- 设计模式之Prototype(原型)
- 设计模式之Prototype(原型)
- 初试WAP之wml+ASP查询
- 点评性能测试工具OpenSTA
- 真受不了sun
- 在MySQL的启动选项中增加default-character-set=gb2312
- 韩文学习
- C#设计模式之原型(ProtoType)
- 理解自然数的定义
- Thinking In Java 学习笔记(序)
- C++中几个比较不常用的关键字(转)
- 使用SQLSERVER的扩展存储过程实现远程备份与恢复
- Tomcat中添加虚拟目录
- 使用Web标准建站第1天:选择什么样的DOCTYPE (copy别人的,以下皆同)
- 新人去了新公司,你应该怎么说话?
- 离开水的鱼