Abstract Factory Pattern
Create instances of classes belonging to different families
Very frequently used and very useful
1 / 5
UML Class Diagram:
- The abstract factory class defines the abstract methods that have to be implemented by concrete factory classes. It serves as interface and contract definition.
- The concrete factory classes contain the real implementation that define which classes are created during run-time.
- Note that the methods return values are also defined by abstract classes, this allows a high flexibility and independence, leading to methods that must only be implemented once.
- The returned classes are however specific to each concrete factory class (you will see their implementation below).
- Here you see the abstract classes that are used during the creation process (a method was added that serves to prove the validity of the design).
- Based on the abstract classes some real example implementation are created, those will be instantiated during run-time, depending on the concrete factory that creates them.
- When implementing the associations between the Driver class, the abstract factory class and the abstract classes you may either use the common language agnostic approach using only private members (which is the most memory efficient one).
- Or you may use the C# language specific approach where everything is wrapped using private properties. This allows adding logic when accessing or changing the private members but might be a little overkill.
- You may also use another C# language specific solution that uses generic classes to create objects and that is also a valid implementation for the abstract factory pattern.
- In the last step we add some code to test the software design and the Abstract Factory implementation.
- When running the example you can see that everything is working as expected and that the correct classes are instantiated during runtime.