Design Pattern - Creational Patterns - Prototype Pattern

50 篇文章 0 订阅
37 篇文章 0 订阅

2007

Section 4, Chapter 2


Prototype Pattern


Concept

The Prototype pattern gives us a way to produce a copy or clone of a class that we already have created and configured. Prototype method is internal to the originating class, and has access to its class's internal variables. This gives the method direct access to both the originating and the new class's internal state. This allows us to capture the present state of the original object in its clone so we can modify the cloned object without introducing those changes to the original.


Use

Creating a new class from scratch would not reproduce the appropriate internal variable values in the new class we desired without violating rules of encapsulation of the class. Simply constructing a new class would not get us the class in its current state. Making a clone of the existing class would allow the clone to be modified and used without changing the original and would allow us to capture the originating class's state in the new class.

Or we cannot create a new class in the current scope of the code or because allowing a constructor on the class in the current scope violates the rules of encapsulation of our application. We could not call the constructor because of its encapsulation properties.


Design

The Prototype pattern has one main component: the Prototype. The prototype is really an ordinary class that has a method implemented to create a copy (or clone) of itself.




Illustration



abstract class Stone
{
	public abstract Stone Clone();
}


class Granite : Stone
{
	public override Stone Clone()
	{
		return (Granite)this.MemberwiseClone();
	}
}


Stone clonedStone = stone.Clone();


Note: The .NET MemberwiseClone() method only provides a shallow copy of the class, below provides a solution of deep cloning.



public override Stone Clone()
{
	Stone ret = (Granite)this.MemberwiseClone();
	foreach(object obj in _collection)
		ret.Add(obj.Clone()); //Reference Type is also cloned
	return ret;
}



December 2007

Section 1, Chapter 5






Vincent's Demonstration


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值