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
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:
Post a Comment