Home
Cloud
Big Data
CI
Install
Samples
Java
Ubuntu
Maven
Archive
Design Patterns
|
Builder
References
Example
The
Product
The
Concrete Product
The
Builder
The
Concrete Builder
The
Director
A simple class to test the
Builder
design pattern
References
Definition: (
source:
http://en.wikipedia.org/wiki/Builder_pattern
)
The intent of the
Builder
design pattern is to separate the construction of a complex object from its representation.
By doing so the same construction process can create different representations.
Class diagram: (
source:
http://en.wikipedia.org/wiki/Builder_pattern
)
Example
The
Product
:
public interface Session { public String sendRequest(final String request); }
The
Concrete Product
:
public class HttpSession implements Session { public String sendRequest(final String request) { return "http response"; } }
The
Builder
:
public interface SessionBuilder { public Session getSession(); public void createSession(); public void configureSession(); }
The
Concrete Builder
:
public class HttpSessionBuilder implements SessionBuilder { private Session session; public Session getSession() { return session; } public void createSession() { this.session = new HttpSession(); // do something else with the created session ... } public void configureSession() { // configure the session ... } }
The
Director
:
public class SessionDirector { private SessionBuilder sessionBuilder; public SessionDirector(final SessionBuilder sessionBuilder) { this.sessionBuilder = sessionBuilder; } public Session build() { sessionBuilder.createSession(); sessionBuilder.configureSession(); return sessionBuilder.getSession(); } }
A simple class to test the
Builder
design pattern:
public class BuilderPatternTest { public static void main(String[] args) { // create the builder final SessionBuilder sessionBuilder = new HttpSessionBuilder(); // create the director final SessionDirector sessionDirector = new SessionDirector(sessionBuilder); // create the session final Session session = sessionDirector.build(); // call methods final String response = session.sendRequest("request"); System.out.println(response); } }
© 2010-2022
mti
tek