Gang-of-Four Creational Design Pattern Examples in Delphi
5 minute read
Delphi versions of the Maze code samples of Creational Design Patterns in “Design Patterns: Elements of Reusable Object-Oriented Software”.
The abstract factory is a class that creates components and returns them to the caller as their abstract types. In this case I chose interfaces over the abstract classes as used in the samples of the book. Any number of concrete classes can implement the factory interface. The consumer in this case does not see the implementation, but just the resultant products.
The builder pattern is similar except that the consumer only sees the highest level of abstraction. Intermediate products are identified in parameters via some kind of index or other key identifier.
Notice that the builder offers a higher level of abstraction
In short its a method that creates a product, the method must be overriden by decendents to extend the base (or sometimes fail-over) product range.
We can add a concrete implementation. We can add any number underneath the abstract creator. Products at the abstract creator level are always available while. Concrete factories will add any number of new products in potentially independent hierarchies. This may pose some risk in requestion products the class cannot create. It also opens up the potential of re-implementation or hiding of base products.
I rarely implement the singleton pattern and rather I prefer a pure abstract class with class properties and class methods. This pattern is particularly tricky in Delphi because you always have at least the constructor at the base TObject level, so it cannot be implemented as defined in the book. The only way to fully hide the constructor is to supply an interface via a class.
This is one of my favorite design patterns. To use it you provide prototype instances during construction. These will then be used to create clones in the factory. This provides extensibility where you have no access to the code (like a user-defined extension or plug-in).