1

What problems are solved by factory design patterns?

I have studied Design Patterns: Elements of Reusable Object-Oriented Software but I still find difficulties to understand and implement it.

If I implement a factory design pattern and each object has one common behaviour and the rest are unique. So whether should I implement a factory design pattern for this or create a plain class?

  • 1
    Can you elaborate what you mean by "each object has one common behavior and the rest are unique" with some examples? I think the factory pattern is most useful in the context of polymorphism. That is, you have a single method on "interface" `A` for creating an object of type `B`, but subclasses of `A` can override the method and return different implementations of `B`. However, the Factory pattern can also be used to map inputs (typically an enumeration of values) to different subclasses represented by those values. Either way, the exact class returned by the method call is obscured. – Dennis Kats Jun 03 '23 at 07:22
  • Hi @DennisKats , Thank you for your response, I really appreciate your time. I mean by "each object has one common behaviour and the rest are unique" is, suppose I have two child classes and each has to colour a toy behaviour but constructing a toy is different for each toy. So in this case, I have one common behaviour among the two child classes which is colouring an object. Also, I will be grateful if you review my article on factory design patterns. https://deepakatariya.com/factory-design-pattern-can-help/ Thank you, Deepak Atariya – Deepak Atariya Jun 04 '23 at 08:54
  • 1
    The factory design pattern isn't relevant in abstracting the behavior of classes. It's used to abstract the creation of said objects such as when (1) subclasses need the ability to override it, or (2) the creation of the objects involves complex initialization logic, or (3) the classes of said objects are encapsulated and restrict direct access. If you have some common behavior in your classes and you want to share the code between them, then you should create an [abstract class](https://stackoverflow.com/a/48428063/8926512). – Dennis Kats Jun 04 '23 at 20:23
  • It is helpful, thank you – Deepak Atariya Jun 05 '23 at 16:25
  • 1
    If you are doing too much if..else on these objects, you need a factory. If they have the same behavior, let's say class A and class B has a calculate(int a, int b) method, you can use a factory to create these objects. But if only few classes has these behavior, it may be an over kill – cerberus Jun 06 '23 at 16:02

0 Answers0