Remix.run Logo
chrchr 4 days ago

The reason to use a factory instead of 'new' is that a factory can vary the return type, unlike a plain constructor. You need a factory when, based on the constructor parameters or the system configuration, different classes of object may be instantiated. I really have to disagree with your characterization of the GoF book. The premise is that it's a set of designs that can be applied when specific situations are encountered, though, granted, if you're reading the book before you've actually seen the situation where a particular pattern can be applied, it seems abstract. Certainly, popular conceptions of patterns taken out of context make that problem worse.

1718627440 4 days ago | parent | next [-]

> a factory can vary the return type, unlike a plain constructor

That's a language limitation and has nothing to do with the design pattern. You can do this just fine e.g. in Python.

idontwantthis 4 days ago | parent [-]

You could do that more or less in Javascript by creating and initializing different member variables in the constructor depending on a constructor argument but I would hate you for it.

scrame 4 days ago | parent | prev [-]

yeah, they say in the introduction even that it is to give a language to common patterns that emerge in C++ style OOP. It gives examples of what it might look like, but isn't an instruction manual on what to do. Its to give a common language "this is a gateway" as opposed to "this is where stuff goes in", or "front-door" or whatever tribal names / descriptions people come up with.