Pattern Name:
Factory Method
Create instances of derived classes
Usage:
Frequently used, fairly easy to implement and useful for centralizing object lifetime management and avoiding object creation code duplication
1 / 5
UML Class Diagram:
Explanation:
- The abstract creator implements a factory method that returns an objects. It also contains a method for testing purposes that serves to validate the design.
- Each concrete creator overrides the abstract factory method and returns a specific object concerning on the context.
- In this example the factory method is used internally to set a property but it could also be used in an external context for creating objects when needed.
- The abstract class defines the interface and class structure for all objects that get build by the specific concrete creators via their factory methods.
- There is also the possibility to create a C# specific solution that uses generics which also results in a valid factory method.
- In the last step we add some code to test the software design and the Factory Method implementation in the language agnostic and in the C# specific versions.
- When running the example you can see that everything is working as expected and that the correct classes are instantiated during runtime.
Source Code:
http://csharpdesignpatterns.codeplex.com/
No comments:
Post a Comment