Thursday, July 27, 2017

Factory Pattern

Much has been written about the Factory-pattern, I assume. Here's my viewpoint on it.

I was puzzled a bit when I first read about it. Why?  Because I was mostly programming in Smalltalk at the time. In Smalltalk the ONLY way you can create objects is by using the Factory Pattern. You create new objects by calling the class-method 'new'. So if you always follow a pattern, it's not really a pattern any more, is it? It's like fish in the water. What is this thing "water" they keep talking about?

I take it a bit further. For a Smalltalker the Factory-pattern is like air. Without it they would be dead. Without it they couldn't create any objects and thus couldn't write any Smalltalk programs and thus couldn't make a living as a Smalltalker.

But it is easy to see the benefits of using Factory (as opposed to not using it) in languages like C++ and Java and JavaScript. You create object-instances  by calling (typically static) methods, not by calling constructors directly. This means you can have more than one such method per class. And you can have more than one class implementing a factory-method of the same name.

In Smalltalk in contrast there are no "constructors". You don't need them _because_  every Smalltalk-class implements the Factory pattern, because the class-method 'new' is inherited to every class, from the root-class Object.

What the Factory pattern does is it abstracts away from the IMPLEMENTATION of the results of the class- (or "static") methods used to produce  the objects. Think about the proverbial  Sausage Factory. You don't really need to know what goes on inside the factory. You only care that you get a Hot Dog when you order one, and you get a Bratwurst when you order that.

Depending on the class upon which you call the (same) class-method the result can be an instance of any number of different classes. You need not care which exact class it is, as long as it behaves like you expect.  And depending on the (different) class-method you call on any of the classes the result can be an instance of a different classes, giving it different properties.

Above may sounds like a complicated descriptions, but it's just trying to express the two main properties, two main features of Factory-pattern:  

1. A Factory can produce multiple different products, depending on what you order
2. There can be multiple factories  which return their own different product even though you make the exact same "order" to each of them .

This separates the implementation = the way a factory manufactures its products, from their specification = what their products are. And it gives you flexibility in deciding whether you create one factory with many products, or many factories each producing just one or a few products.

Factory Method Pattern (Wikipedia)


Copyright © 2017 Panu Viljamaa. All rights reserved