Factory Method Pattern

udaiveer singh
Code Wave
Published in
3 min readJun 21, 2019

If you ask a developer if they know what factory pattern is you will usually get a “yea I know that pattern”. I was one of those developers… and I was also wrong about claiming to know the factory pattern.

For me, a factory pattern was just a static class that returns an object.

Just to demonstrate what is not a factory pattern let me show an example.

public static class Foo {public static Foo makeFoo() { return new Foo(...); }}

you can get fancy and have some case statements

public static Foo makeFoo(FooEnumType em) { 
switch(em) {
case(FooEnumType1): return new Foo1(...)
case(FooEnumType2): return new Foo2(...)
case(FooEnumType3): return new Foo3(...)
default throw new RuntimeException("omg plz stop")
}
}

now is that a factor pattern…? Well, the answer is no, this is not really a pattern at all. A design pattern needs to ideally have or satisfy all 5 parts of the SOLID principles while this class only satisfies the first rule which is (single responsibility) and literally violates every other principle.

There are actually 2 factory patterns

In this article, I just going to focus on the simpler factory pattern which is called the Method Factory Pattern.

What is the method factory pattern?

A factory method pattern is a strategy that is used to organize the creation of objects in such a way that what you create does not interfere with how it is used in your application

When to use the method factory pattern?

Use this pattern when you have different kinds of objects that you want to create that have the same common functionality ie. share an (interface, common subclass, trait…) but can vary in concrete implementations. For example, if you are building a car game and you have 3 types of cars (hot-rod, tuner, exotic), you should be able to make car interface and have the implementation depend on the car interface.

How to use the method factory pattern?

If you have any application code, it should never refer to concrete implementations. Your application is your high-level policy (abstractions) and in this application, the Button/Dialog are the high-level policy and the rest of the classes are implementation details.

According to Rober C. Martin’s Clean Code Book

Hight level policy should never depend on implementation details.

This pattern helps with that as well as promotes good dependency management practices and helps to keep your application compliant with the SOLID principles.

Ok ok, there is one big loophole here and I thought I should mention it. The UML looks good and pretty, but if you were to write this application you have to at some point do (Dialog d = new WindowsDialog) so does that mean you have violated the principles laid out by Martin?

I will cover that issue in the next blog post. =)

Hint: one way around this is to use reflection

sources:

--

--