DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Securing Your Software Supply Chain with JFrog and Azure
Register Today

Trending

  • TDD vs. BDD: Choosing The Suitable Framework
  • SRE vs. DevOps
  • How to Implement Istio in Multicloud and Multicluster
  • Constructing Real-Time Analytics: Fundamental Components and Architectural Framework — Part 2

Trending

  • TDD vs. BDD: Choosing The Suitable Framework
  • SRE vs. DevOps
  • How to Implement Istio in Multicloud and Multicluster
  • Constructing Real-Time Analytics: Fundamental Components and Architectural Framework — Part 2

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.

Avraam Piperidis user avatar by
Avraam Piperidis
CORE ·
Updated Jan. 02, 20 · Review
Like (1)
Save
Tweet
Share
10.22K Views

Join the DZone community and get the full member experience.

Join For Free

car being built in a factory

Find out more about Factory and Builder Design patterns.


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.

You may also like: Decorator Design Patterns

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.

Java




xxxxxxxxxx
1
10


 
1
public class StudentBuilder 
2
{private Student student; public StudentBuilder() 
3
{student = new Student(); } public StudentBuilder withName(String name)
4
{student.setName(name); return this;}
5
 public StudentBuilder withLastName(String lastName)
6
 {student.setLastName(lastName); return this; } 
7
 public StudentBuilder withAge(int age)
8
 { student.setAge(age); return this; } 
9
 public Student build() { return student; } }
10
 
          



We use it like this.

Java




xxxxxxxxxx
1


 
1
public static void main(String s)
2
{ StudentBuilder builder = new StudentBuilder() 
3
  .withName("John") .withLastName("Appleyard") 
4
  .withAge(22); Student student = builder.build(); }
5
 
          



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.

Java




xxxxxxxxxx
1
40


 
1
public interface Tab {
2
}
3
 
          
4
// A Left tab 
5
public class LeftTab implements Tab {
6
    public string Position;
7
}
8
 
          
9
// A Right Tab
10
public class RightTab implements Tab {
11
    public string Position;
12
}
13
 
          
14
public interface TabFactory {
15
    Tab create();
16
}
17
 
          
18
// A Left tab specific factory that implements TabFctory
19
public class LeftTabFactory implements TabFactory {
20
    @Override
21
    public Tab create(){
22
        return new LeftTab(){Position:'LEFT'};
23
    }
24
}
25
 
          
26
// A Right tab specific factory implements TabFactory
27
public class RightTabFactory implements TabFactory {
28
    @Override
29
    public Tab create() {
30
        return new RightTab(){Position:'RIGHT'}
31
    }
32
}
33
 
          
34
// Use case
35
public static void main(String[] a){
36
    TabFactory leftTabFactory = new LeftTabFactory();
37
    TabFactory rightTabFactory = new RightTabFactory();
38
    Tab leftTab = leftTabFactory.create();
39
    Tab rightTab = rightTabFactory.create();
40
}



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.

Java




xxxxxxxxxx
1


 
1
public interface DbConnection { void commit(); ... } 
2
public class MySqlConnection implements DbConnection { @Override public void commit(){} } 
3
public class OracleConnection implements DbConnection { @Override public void commit(){} } 
4
public class PostGresConnection implements DbConnection { @Override public void commit(){} } 
5
public class DbConnectionFactory { public static DbConnection createConnection(String type) 
6
{ switch(type){ case "ORACLE" : return new OracleConnection(); case "MYSQL" : return new MySqlConnection(); 
7
case "POSTGRES" : return PostGresConnection(); } return null; } } 
8
// Use case public static void main(String[] a){ DbConnection oracleCon = DbConnectionFactory.createConnection("ORACLE"); DbConnection mysqlCon = DbConnectionFactory.createConnection("MYSQL"); }
9
 
          



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

Design Patterns in Java: Singleton

Design Patterns Microservices

Strategy vs. Factory Design Patterns in Java

Factory (object-oriented programming) Design

Published at DZone with permission of Avraam Piperidis, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Trending

  • TDD vs. BDD: Choosing The Suitable Framework
  • SRE vs. DevOps
  • How to Implement Istio in Multicloud and Multicluster
  • Constructing Real-Time Analytics: Fundamental Components and Architectural Framework — Part 2

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: