
.NET 1.1+Prototype Design Pattern (2)
The prototype design pattern is a design pattern that is used to instantiate a class by copying, or cloning, the properties of an existing object. The new object is an exact copy of the prototype but permits modification without altering the original.
Example Prototype
The prototype design pattern is generally used for complex classes or for classes that are costly to instantiate. In this example, we will use a simple class to keep the code to a manageable size. The base prototype class represents an employee of a business. This class incorporates two properties to hold the employee's name and role. It also, of course, includes the Clone method.
Two concrete classes are created to represent typists and software developers. Each inherits from the employee prototype base class and adds an extra property for the specific subclass. As both classes contain only value types and strings, it is acceptable to use MemberwiseClone for copying. If reference types were included and needed to be duplicated, rather than just copying the reference, manual cloning of each property would be required. Finally, the ToString method for each class is overridden to make it easier to output details of the objects.
NB: For brevity the properties are defined using the .NET 3.0 automatically implemented property syntax. For earlier versions of the .NET framework, these must be expanded.
public abstract class Employee
{
public abstract Employee Clone();
public string Name { get; set; }
public string Role { get; set; }
}
public class Typist : Employee
{
public int WordsPerMinute { get; set; }
public override Employee Clone()
{
return (Employee)MemberwiseClone();
}
public override string ToString()
{
return string.Format("{0} - {1} - {2}wpm", Name, Role, WordsPerMinute);
}
}
public class Developer : Employee
{
public string PreferredLanguage { get; set; }
public override Employee Clone()
{
return (Employee)MemberwiseClone();
}
public override string ToString()
{
return string.Format("{0} - {1} - {2}", Name, Role, PreferredLanguage);
}
}
3 September 2008