Reputation: 1415
can anyone explain why we need to use MemberwiseClone() in prototype pattern?
public abstract class AProtagonistEx
{
int m_health;
int m_felony;
double m_money;
// This is a reference type now
AdditionalDetails m_details = new AdditionalDetails();
public int Health
{
get { return m_health; }
set { m_health = value; }
}
public int Felony
{
get { return m_felony; }
set { m_felony = value; }
}
public double Money
{
get { return m_money; }
set { m_money = value; }
}
public AdditionalDetails Details
{
get { return m_details; }
set { m_details = value; }
}
public abstract AProtagonistEx Clone();
}
class CJEx : AProtagonistEx
{
public override AProtagonistEx Clone()
{
**return this.MemberwiseClone() as AProtagonistEx;**
}
}
By default all the properties and methods of the parent class can be access in the child class. then what is the need of this pattern?
Upvotes: 1
Views: 1369
Reputation: 1
MemberwiseClone
Is I’m used to make the shallow copy of an object.
Reference type members(example string) of both copied and the original object will have to same reference. So if user modifies one, it will change the other as well.
To make the deep copy user need to add a custom copy method. So that both members will have different references.
Upvotes: 0
Reputation: 726569
Prototype Design Pattern is about instances, not about classes. Instances of CJEx
class do indeed inherit all properties and methods of their base class through inheritance. However, the prototype pattern is concerned with the values of the properties, not simply with having the properties on the object.
In fact, this is the difference between the prototype pattern and the abstract factory pattern: the prototype pattern pre-populates your properties in the way they are set in the prototype object, while abstract factory gives you an object with properties that set to default values or the values that you provided in the call.
Upvotes: 4