Chapter 5. Creational Patterns: Prototype, Factory Method, and Singleton
The creational patterns aim to separate a system from how its objects are created, composed, and represented. They increase the system’s flexibility in terms of the what, who, how, and when of object creation. Creational patterns encapsulate the knowledge about which classes a system uses, but they hide the details of how the instances of these classes are created and put together. Programmers have come to realize that composing systems with inheritance makes those systems too rigid. The creational patterns are designed to break this close coupling. In this and the following chapter, we shall make further use of some C# features that help to abstract the instantiation process—generics and delegates (introduced in Chapter 3 and Chapter 4, respectively) are two of these.
We’ll start by looking at three small patterns that are helpful in combination with many others. The Prototype pattern ensures that when copies of complex objects are made, they are true copies. The Factory Method pattern is a means of creating objects without knowing the exact subclass being used. Finally, the Singleton pattern ensures that only one of a class can be built and that all users are directed to it.
The Prototype pattern creates new objects by cloning one of a few stored prototypes. The Prototype pattern has two advantages: it speeds up the instantiation of very large, dynamically loaded classes (when copying objects ...