Friday, May 6, 2011

[Tutorial] Common Design Patterns in C# 4.0
Part4: Factory Method Pattern

Pattern Name:
Factory Method

Short Description: 
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

Complexity:
1 / 5

UML Class Diagram:

image

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.

image

  • The abstract class defines the interface and class structure for all objects that get build by the specific concrete creators via their factory methods.

image

  • There is also the possibility to create a C# specific solution that uses generics which also results in a valid factory method.

image

image

  • 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.

image

  • When running the example you can see that everything is working as expected and that the correct classes are instantiated during runtime.

image

Source Code:
http://csharpdesignpatterns.codeplex.com/


Share/Save/Bookmark

No comments: