Sunday, May 1, 2011

[Tutorial] Common Design Patterns in C# 4.0
Part2: Abstract Factory Pattern

Pattern Name:
Abstract Factory Pattern

Short Description:
Create instances of classes belonging to different families

Usage:
Very frequently  used and very useful

Complexity:
1 / 5

UML Class Diagram:

image

Explanation:

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

image_thumb1[2]

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

image_thumb5[1]

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

image_thumb3[1]

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

image_thumb11[1]

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

image

  • In the last step we add some code to test the software design and the Abstract Factory implementation.

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: