Saturday, September 19, 2009

The Abstract Factory Pattern provides an interface for creating families of related objects without specifying their concrete classes. The Abstract Pattern makes sure that the client does not know anything about the objects being created. The pattern hides the implementation of the product definitions and their class names and the only way the client can create a product is through the factory.

Let’s discover the benefits of this Pattern using CppDepend, and for that we analyze the following example.

in this example we have a code source before and after refactoring, you can copy the code into two distincts files factorybefore.cpp and factoryafter.cpp.

CppDepend Analysis

To analyze this example with CppDepend, do the following steps:

- Lanch VisualCppDepend.exe and create new project.
- Use “Create Project Description “ Button to lauch the project maker wizard



- Add Project to solution.
- Add Files to project created



- Save as “Factory.sl”
- In VisualCppDepend use “Browse” button to specify Factory.sl file.
- Launch the analysis.

After the analysis of the example before using factory pattern, we analyze it after the modifications, for that we have to change the description of the project by removing “factorybefore.cpp” and adding “factoryafter.cpp”.

CppDepend provide an interesting functionality to compare between two version, in our case we compare the project before and after refactoring and there's the result.




we can see that there are some added new classes in the browser characterized by the Bold Style and there's also a modification in dependency matrix.

Where WindowsButton class is created?

To answer to this question let’s execute the following CQL request:

SELECT METHODS WHERE CreateA "WindowsButton" ORDER BY DepthOfCreateA

Before:



After:



So we can observe that before refactoring, the class is created in many places, but after refactoring the creation is isolated in WindowsFactory, the responsibility of the creation is now isolated and it impact the cohesion, so we have a high cohesion than before.

What the impact for coupling?

Using Matrix can help to detect coupling between projects and classes.



If you look at the intersection between main method and MotifButton class we observe a red “-“sign, so we lose a dependency between Main and other classes like WindowsButton, MotifButton.

Let’s discover the dependency graph before and after:

Before:



After:




So the global methods are now isolated form concretes classes used, and we have a low coupling so we can add another family of classes without changing the client that use them, only the factory will be changed.

Conclusion:

Abstract Factory can improve the cohesion and coupling of classes.

No comments:

Post a Comment