6

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?

2 Answers 2

2

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

0

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
  • 1
    Shouldn't your interface define a runBrowser method? Oct 14, 2012 at 16:47
  • 1
    Shouldn't a factory create something? So something like getBrowser(): IBrowser which might then have a function run(). Oct 16, 2014 at 16:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.