0

Suppose we want to create button and text area.

We can whether create them for Windows or Mac.

As I understood, there are two "switch" or "if" statements, one for selecting the desired factory and one for selecting the desired product.

But if I want to add "Linux" factory and "Text field" product, should I edit the code and add this third option to the "if" or "switch" statements?

Isn't it violating the open/close principle?

1 Answers1

0

There are no switch or if statements in an Abstract Factory; however, there is an enormous amount of misinformation regarding factory patterns, so misunderstandings are common. What are the differences between Abstract Factory and Factory design patterns? may help in that regard.

Nevertheless, the Abstract Factory pattern is still prone to OCP violations because, as you've noted, there is no obvious way to add new products. The GoF book does address this limitation and offer a potential solution. See: Is there "more" real world example of Abstract Factory pattern?

jaco0646
  • 15,303
  • 7
  • 59
  • 83
  • Thanks for your reply. I checked the links you sent, but the problem for me is that it seems nobody used these implementations of AF in the `main` function. I implemented AF using `switch` statements and in the `main` function I created a button this way: `Button uiElement =(Button)UiFactory.CreateUiFactory("Windows").CreateUiElement("Button");` But now I think the AF only creates an interface to dictate to other factories what requirements they should fulfill, e.g., all UI factories should created "button" and "textarea" in my example. Am I right? – Hamed Homaee Mar 19 '21 at 15:40
  • In that case, I would say what you (and others) have implemented is not the Abstract Factory pattern; and the answer to the question, "_Isn't it violating the open/close principle?_" is simply, _yes_. The best descriptions and examples of the pattern are in the first linked thread above. You are correct that it is an interface to define related products. – jaco0646 Mar 19 '21 at 15:47