Aim of Factory pattern is to stop us from over-riding or re-writing the functions which instantiate?

softwareengineering.stackexchange https://softwareengineering.stackexchange.com/questions/340036

  •  05-01-2021
  •  | 
  •  

Pergunta

http://www.cs.unc.edu/~stotts/GOF/hires/pat3cfso.htm

CreateMaze is the function which instantiates the objects. IMO, according to factory pattern we are not supposed to overload or modify or re-write the function which instantiates objects.

But in the example, the CreateMaze function returns a Maze*. So, now if we have to write an EnchangedMaze class, will we have to re-write CreateMaze function to return a pointer of EnchantedMaze?

From: http://www.cs.unc.edu/~stotts/GOF/hires/chap3fso.htm

Changing the layout means changing this member function, either by overriding it—which means reimplementing the whole thing—or by changing parts of it—which is error-prone and doesn't promote reuse.

Isn't this what factory pattern wants to avoid?

What point am I missing?

Foi útil?

Solução

You've misunderstood the purpose of the pattern.

The point of a pattern is never that you're not supposed to change anything ever again. You're the author of the system, when the requirements change (and they will change), you will have to change the corresponding parts. No class is safe from that.

The specific point of the factory pattern is that a client program (possibly written by someone else) doesn't have to know the specific type that the factory returns, but only the interface that it was written to. That way, when the factory owner changes the Car implementation from GasGuzzlerCar to ElegantElectricCar, the client program does not have to be rewritten because it only uses the type Car.

The alternative would be for the vendor to export the type GasGuzzlingCar and then breaking all clients whenever that type changes. That is clearly the inferior solution. So you see, the purpose of the factory is to insulate clients of a library against changes within the library, particularly changes that could leak outside the library via type declarations.

Outras dicas

"Factory" indeed introduces a method that is not supposed to be modified or overridden. "Factory Method" on the other hand is a completely different pattern, a special case of "Abstract Factory". The only thing that is common between "Factory" and "Abstract Factory" is they are both creational patterns.

There is no contradiction in linked article as it does not describe "Factory".

Licenciado em: CC-BY-SA com atribuição
scroll top