Everything You Need to Know About Factory and Builder Design Patterns
The Builder and Factory design patters, what they are, where to use them, how to make them with code samples and what are their differences.
Join the DZone community and get the full member experience.
Join For Free
Intro
This article focuses on the Builder and Factory design patters, what they are, where to use them, how to make them with code samples and what are their differences.
Both factory and builder design patters are categorized in Creational Design Patterns.
That means both will take the responsibility to create an object for you, abstracting the process of how the object is built.
The Builder Design Pattern
In a builder, we usually call a static builder method or we instantiate a builder and chain call the methods until we build the desired object we want.
Below we have a very simple example of a builder pattern.
xxxxxxxxxx
public class StudentBuilder
{private Student student; public StudentBuilder()
{student = new Student(); } public StudentBuilder withName(String name)
{student.setName(name); return this;}
public StudentBuilder withLastName(String lastName)
{student.setLastName(lastName); return this; }
public StudentBuilder withAge(int age)
{ student.setAge(age); return this; }
public Student build() { return student; } }
We use it like this.
xxxxxxxxxx
public static void main(String s)
{ StudentBuilder builder = new StudentBuilder()
.withName("John") .withLastName("Appleyard")
.withAge(22); Student student = builder.build(); }
As we can see we create a StudentBuilder instance and we chain call the methods we want, for example withName
, withLastName
and withAge
. In the end, we call builder.build()
which is the final step and take the responsibility to create and give us the object we want.
The Factory Design Patterns
We can separate factory design patterns into two main categories.
Abstract Factory Pattern.
Factory Method Pattern.
Generally, in factories, we don't have much control over the object's creation process. Also, the configuration of the object we can set is restricted usually on the factory constructor or method.
Abstract Factory Pattern
Now let's take a look at Abstract Factory Pattern.
Abstract factory patterns use inheritance.
xxxxxxxxxx
public interface Tab {
}
// A Left tab
public class LeftTab implements Tab {
public string Position;
}
// A Right Tab
public class RightTab implements Tab {
public string Position;
}
public interface TabFactory {
Tab create();
}
// A Left tab specific factory that implements TabFctory
public class LeftTabFactory implements TabFactory {
public Tab create(){
return new LeftTab(){Position:'LEFT'};
}
}
// A Right tab specific factory implements TabFactory
public class RightTabFactory implements TabFactory {
public Tab create() {
return new RightTab(){Position:'RIGHT'}
}
}
// Use case
public static void main(String[] a){
TabFactory leftTabFactory = new LeftTabFactory();
TabFactory rightTabFactory = new RightTabFactory();
Tab leftTab = leftTabFactory.create();
Tab rightTab = rightTabFactory.create();
}
As we can see in main
method, to create a left tab we need a left tab factory, and to create a right tab we need a right tab factory.
Right or left tab factory is still a tab factory so we using/depending on TabFactory
interface and the factory implementation is what we want.
In the future, we can add with safety another type of factory eg. CenterTabFactory
which will implement TabFactory
.
Factory Method Pattern
In a factory method, we usually end up calling a single method by providing some kind of info data.
xxxxxxxxxx
public interface DbConnection { void commit(); ... }
public class MySqlConnection implements DbConnection { public void commit(){} }
public class OracleConnection implements DbConnection { public void commit(){} }
public class PostGresConnection implements DbConnection { public void commit(){} }
public class DbConnectionFactory { public static DbConnection createConnection(String type)
{ switch(type){ case "ORACLE" : return new OracleConnection(); case "MYSQL" : return new MySqlConnection();
case "POSTGRES" : return PostGresConnection(); } return null; } }
// Use case public static void main(String[] a){ DbConnection oracleCon = DbConnectionFactory.createConnection("ORACLE"); DbConnection mysqlCon = DbConnectionFactory.createConnection("MYSQL"); }
The factory method is more simple to implement and use.
We can simply use DbConnectionFactor
by calling the static method createConnection
and pass the parameter to get the object we want.
Drawback
One drawback of the factory method, especially in the example above is the resulted violation of the O of SOLID (O stands for Open–Closed Principle).
Factory Method or Abstract Factory?
There is a lot of things one should consider before choosing between the factory method and abstract factory.
The most important thing is that the abstraction level of the abstract factory is higher than the factory method.
So if there is a lot of refactoring and new types of implementation added often, then the Abstract Factory is to go, since it won't require code refactoring because of factory method 'if cases'.
Conclusion
It's up to you to choose, depending on the freedom you want to give.
Also, these two can be combined together with composition. A Builder can have a factory or the other way around. For example, we can use a builder and a factory inside to choose what to implement. Just try to keep it simple.
A good way to exercise and create builders and factories is to implement them in unit tests. Usually, in unit tests, a lot of classes need to be initialized and pre-configured, so why not use builders and factories or maybe combine them with mockito?
Also, keep in mind that is a good idea to depend on interfaces and not on concrete implementations.
Further Reading
Published at DZone with permission of Avraam Piperidis, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments