re: Explain Factory Pattern Like I'm Five VIEW POST

VIEW FULL DISCUSSION
 

When a person makes something, for example a fork, it takes them a certain amount of time. If the person has to make a lot of forks then, if they try to do so quickly, each fork can come out with differences between them and even things wrong. Perhaps some of the forks are shorter than others, or maybe some break more easily. If the person takes their time to make each fork they will be able to make them all to a similar standard, but they won't be able to make very many.

If you look at the fork in our cutlery draw you can see that they all look the same and none of them break. If you go to a shop to buy forks, you'll see there are lots of forks. Always more forks than there are people who need them. If it takes a lot of time for a person to make a fork well, how did we get so many forks?

What happened was that someone came up with a machine that can take metal and turn it into a fork. This machine can work faster than a person because it only has to do one thing: make forks. The machine will melt the metal, pour it into a mould that is the shape of a fork and once the metal has cooled there will be a new fork.

In fact, the machine will be made to make many forks at once. It will be made to take many different shapes of fork mould. Not all forks look the same, after all.

The building this fork making machine is in is called a factory. Shops send orders to the factory telling it how many and what shape forks they want. Then we go out and buy forks.

In programming almost none of this is relevant. The thing we call a "factory" is nothing like a factory. It can only produce one thing at a time and we get the thing directly from the factory, not from a shop. It's more like one of the machines that would live in the factory, but limited to producing one of the things at once.

The programmers factory (let's call it a phactory) is a way of producing a thing that is basically one type of thing, for example a user, but has some specific behavioural difference, for example, a user that logs in via OIDC, or a user that logs in via the regular username/password combo.

So our phactory would look something like

   class UserPhactory():
       def get_user(login_type):
           if login_type == 'OIDC':
               return OIDCUser()

           if login_type == 'normal':
               return User()
code of conduct - report abuse