I’m learning the 23 design patterns of the GoF.
I think I’ve found a way to understand and simplify how the Abstract Factory works but I would like to know if this is a correct assumption or if I am wrong.
What I want to know is if we can see the result of the Abstract Factory method as a matrix of possible products where there’s a Product for every “Concrete Factory” x “AbstractProduct” where the Concrete Factory is a single implementation among the implementations of an AbstractFactory and an AbstractProduct is an interface among the interfaces to create Products.
Is this correct or am I missing something?
In short, the abstract factory pattern is a way of encapsulating a group of factories which have a common theme. It utilizes generic interfaces to allow it to create concrete objects which are part of the common theme. Using this pattern you can interchange concrete classes without changing the code that uses them.
The Generics in C# and equivalent constructs in C/C++ or Java are very handy when creating factory pattern. Here is a comprehensive article on how to create a Generic Abstract Factory with C#.
Imagine that in your app you need to open a browser and it depends on the operating system. You can write:
if (operatingsystem == "win32") runExplorer();
else if (operatingsystem == "linux") runKonqueror();
…
or, with AbstractFactory:
interface OperatingSystemAF {
public void runBrowser();
}
class WindowsCC implements OperatingSystemAF {
public void runBrowser() {
//TODO run Explorer
}
}
class LinuxCC implements OperatingSystemAF {
public void runBrowser() {
//TODO run Konqueror
}
}
and main application invokes runBrowser
from OperatingSystemAF
.
2