Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Factory Method Design Pattern seems to just be an If/Else or Switch statement. What am I missing?

So I have been trying to brush up on my design patterns (thank you college for not teaching these...) and the Factory Method design pattern is giving me trouble.


Will refer to this Factory Method Design Pattern In C# for the sake of keeping the question area from having a ton of code in it. I have no personal code, just trying to understand design patterns


I understand that there are a few parts to it:

  1. Product - CreditCard
  2. ConcreteProduct- MoneyBackCreditCard, TitaniumCreditCard, PlatinumCreditCard
  3. Creator- CardFactory
  4. ConcreteCreator- MoneyBackCardFactory, TitaniumCardFactory, PlatinumCardFactory

When I look at the implementation though, all I see is a set of objects (with a common ancestor) whose constructor is decided and called based on some variable.

I assume there is something more correct? Last I knew, creating an object in a if/else or switch statement did not define a design pattern. I don't understand what makes this special.

Thanks to all who respond.

like image 209
Shaitan Avatar asked Dec 05 '25 13:12

Shaitan


1 Answers

The refered article does not offer a good explanation of Factory Method pattern. In the UML diagram there is the AnOperation method but in the code there is not. Actually that method is the most interesting point of Factory Method pattern.

The motivation of this pattern is that, in some AnOperation method of a class, you want to create a new instance of another class in a flexible way. At first, you simply instance it by using the new keyword. But later on, as your program elvoves, you find that it is not flexible enough since the class mentioned after the new keyword must be always a concrete class. So you abstract this creation into an abstract method and let derived classes implement it. This is called Factory Method pattern. You can even achieve more flexibility by putting such abstract methods into a separated class/interface. This is called Abstract Factory pattern and of course it is more complex.

The if/else/switch/case statements in the article are totally unrelated to Factory Method pattern. The pattern does not concern which concrete factory is selected by users, that's a different story. Usually this selection happens in the CompositionRoot of your program. The main method is such a place.

like image 156
Nghia Bui Avatar answered Dec 07 '25 02:12

Nghia Bui



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!