Learn IT

Free learning anything to everything in Information Technology.

Prototype Design Pattern

A Prototype Pattern is a creational design pattern used in software development when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects. This pattern is used for example
to avoid subclasses of an object creator in the client application, like abstract factory pattern does.
or when the inherent cost of creating a new object in the standard way (e.g., using the 'new' kkeyword) is prohibitively expensive for a given application.

C# sample code


public enum RecordType
{
Car,
Person
}

///
/// Record is the Prototype
///

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

///
/// PersonRecord is the Concrete Prototype
///

public class PersonRecord : Record
{
string name;
int age;

public override Record Clone()
{
return (Record)this.MemberwiseClone(); // default shallow copy
}
}

///
/// CarRecord is another Concrete Prototype
///

public class CarRecord : Record
{
string carname;
Guid id;

public override Record Clone()
{
CarRecord clone = (CarRecord)this.MemberwiseClone(); // default shallow copy
clone.id = Guid.NewGuid(); // always generate new id
return clone;
}
}

///
/// RecordFactory is the client
///

public class RecordFactory
{
private static Dictionary _prototypes =
new Dictionary();

///
/// Constructor
///

public RecordFactory()
{
_prototypes.Add(RecordType.Car, new CarRecord());
_prototypes.Add(RecordType.Person, new PersonRecord());
}

///
/// The Factory method
///

public Record CreateRecord(RecordType type)
{
return _prototypes[type].Clone();
}
}

0 comments: