Builder pattern in Java

Builder falls under the type of creational pattern category. Builder pattern helps us to separate the construction of a complex object from its representation so that the same construction process can create different representations. Builder pattern is useful when the construction of the object is very complex. The main objective is to separate the construction of objects and their representations. If we are able to separate the construction and representation, we can then get many representations from the same construction.

Figure: – Builder concept

To understand what we mean by construction and representation lets take the example of the below ‘Tea preparation’ sequence.

You can see from the figure ‘Tea preparation’ from the same preparation steps we can get three representation of tea’s (i.e. Tea with out sugar, tea with sugar / milk and tea with out milk).

Figure: – Tea preparation

Now let’s take a real time example in software world to see how builder can separate the complex creation and its representation. Consider we have application where we need the same report to be displayed in either ‘PDF’ or ‘EXCEL’ format. Figure ‘Request a report’ shows the series of steps to achieve the same. Depending on report type a new report is created, report type is set, headers and footers of the report are set and finally we get the report for display.

 

Figure: – Request a report

Now let’s take a different view of the problem as shown in figure ‘Different View’. The same flow defined in ‘Request a report’ is now analyzed in representations and common construction. The construction process is same for both the types of reports but they result in different representations.

Figure: – Different View

We will take the same report problem and try to solve the same using builder patterns. There are three main parts when you want to implement builder patterns.

• Builder: – Builder is responsible for defining the construction process for individual parts. Builder has those individual processes to initialize and configure the product.
• Director: – Director takes those individual processes from the builder and defines the sequence to build the product.
• Product: – Product is the final object which is produced from the builder and director coordination.

First let’s have a look at the builder class hierarchy. We have a abstract class called as ‘ReportBuilder’ from which custom builders like ‘ReportPDF’ builder and ‘ReportEXCEL’ builder will be built.

 

Figure: – Builder class hierarchy

Figure ‘Builder classes in actual code’ shows the methods of the classes. To generate report we need to first Create a new report, set the report type (to EXCEL or PDF) , set report headers , set the report footers and finally get the report. We have defined two custom builders one for ‘PDF’ (ReportPDF) and other for ‘EXCEL’ (ReportExcel). These two custom builders define there own process according to the report type.

Figure: – Builder classes in actual code

Now let’s understand how director will work. Class ‘clsDirector’ takes the builder and calls the individual method process in a sequential manner. So director is like a driver who takes all the individual processes and calls them in sequential manner to generate the final product, which is the report in this case. Figure ‘Director in action’ shows how the method ‘MakeReport’ calls the individual process to generate the report product by PDF or EXCEL.

The third component in the builder is the product which is nothing but the report class in this case.

 

Figure: – The report class

Now let’s take a top view of the builder project. Figure ‘Client,builder,director and product’ shows how they work to achieve the builder pattern. Client creates the object of the director class and passes the appropriate builder to initialize the product. Depending on the builder the product is initialized/created and finally sent to the client.

Figure: – Client, builder, director and product 

The output is something like this. We can see two report types displayed with their headers according to the builder.

Figure: – Final output of builder

 

 

Source -http://ashishkhandelwal.arkutil.com/?p=1076

Pin it

Three main categories of design patterns?


There are three basic classifications of patterns Creational, Structural, and Behavioral patterns.
Creational Patterns

• Abstract Factory:- Creates an instance of several families of classes
• Builder: – Separates object construction from its representation
• Factory Method:- Creates an instance of several derived classes
• Prototype:- A fully initialized instance to be copied or cloned
• Singleton:- A class in which only a single instance can exist

Note: – The best way to remember Creational pattern is by ABFPS (Abraham Became First President of States).
Structural Patterns

• Adapter:-Match interfaces of different classes.
• Bridge:-Separates an object’s abstraction from its implementation.
• Composite:-A tree structure of simple and composite objects.
• Decorator:-Add responsibilities to objects dynamically.
• Façade:-A single class that represents an entire subsystem.
• Flyweight:-A fine-grained instance used for efficient sharing.
• Proxy:-An object representing another object.

Note : To remember structural pattern best is (ABCDFFP)
Behavioral Patterns

• Mediator:-Defines simplified communication between classes.
• Memento:-Capture and restore an object’s internal state.
• Interpreter:- A way to include language elements in a program.
• Iterator:-Sequentially access the elements of a collection.
• Chain of Resp: – A way of passing a request between a chain of objects.
• Command:-Encapsulate a command request as an object.
• State:-Alter an object’s behavior when its state changes.
• Strategy:-Encapsulates an algorithm inside a class.
• Observer: – A way of notifying change to a number of classes.
• Template Method:-Defer the exact steps of an algorithm to a subclass.
• Visitor:-Defines a new operation to a class without change.

Note: – Just remember Music……. 2 MICS On TV (MMIICCSSOTV).

Implementing Log4J

User log4j and commons-logging.jar in the class path. These jar files contain the information for logging set up.Declare the following as a class

attribute in the class where you want to implement the logging, say SomeClass.java

private static Logger logger = Logger.getLogger

(com.mattiz.SomeClass.class);

You would have a sample log4j properties configuration file which you should put in your classpath.
Suppose you wanted the line “Test Debug” to go to your log

file use logger.error or logger.debug or logger.warn.
Viz. logger.error(“Test Debug”);

For warning/ debugging messages you could use

logger.warn(“This is a warning”);

or

logger.debug(“Variable value is”+var);

In the log4j configuration file you can set the level of logging.In the sample configuration file you will find words like ERROR,WARN or DEBUG.If you
set the level to WARN, then only warnings and errors will print, while debug won’t print. If you set the level to DEBUG level then debug, warn and error
will print.These may go to the console or to a separate log output file based on the settings in the log4j configuration file. The log4j.properties contains
settings to “rollover” files. If file becomes more than 1 MB then copying to another file and creating a new file is done automatically by log4j. With the
settings in the log4j.properties file you can control

what is being logged. By setting it to ERROR level, debug statements won’t be printed in the production system.For development use DEBUG level because you
want to see debug messages.

The hierarchy is

DEBUG < INFO < WARN < ERROR < FATAL

If set to WARN level, all warn, error and fatal messages will be printed but no info and debug messages will be printed.You can set logging levels for each
package. So if you are working on a certain package you can set the package’s logging level to DEBUG, and another package’s logging level to WARN in the
log4j properties file.

For example

log4j.category.com.mattiz.security = WARN

You need not use all the debugging levels; mostly people use

DEBUG and ERROR. You can put error level messages inside the catch block.Error logs are like this logger.error(“Exception critical”+ex.toString());You can do this for production systems.

Contents of a simple log4j.properties configuration file

# Print FATAL, ERROR and WARN messages – do not print

DEBUG and INFO messages

# the sequence is FATAL > ERROR > WARN > DEBUG > INFO

# since the level is set to WARN – message levels above it will

be printed

# while levels below it will not be printed

log4j.rootCategory=WARN, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender

log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

# the conversion pattern will be used to format the timestamp

see below example

# 2004-05-13 17:15:13,318 [Servlet.Engine.Transports : 1]

DEBUG

# this will pre-pend all logging messages

log4j.appender.stdout.layout.ConversionPattern=%d [%t] %-

5p %c{1} - %m%n

Contents of a more elaborate log4j.properties file

# the general level is set to WARN

# WARN, ERROR, FATAL will be printed

# In addition to printing to System Out, also print

to "RollingFile"

log4j.rootCategory=WARN, stdout, RollingFile

# the level for the com.mattiz.web package (and subpackages)

is set to DEBUG

# DEBUG, WARN, ERROR, FATAL will be printed for the web package

log4j.category.com.mattiz.web=DEBUG

log4j.appender.stdout=org.apache.log4j.ConsoleAppender

log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

# Print the date and time for systemOut

log4j.appender.stdout.layout.ConversionPattern=%d [%t] %-5p %c{1} - %m%n

# Save log to Rolling File Also

log4j.appender.RollingFile=org.apache.log4j.RollingFileAppender

# Location of rolling file

log4j.appender.RollingFile.File=d:/mattiz/mattiz.log

# if the file becomes greater than 500KB then create a new file

and backup the old file

log4j.appender.RollingFile.MaxFileSize=500KB

# Keep 5 back up files

log4j.appender.RollingFile.MaxBackupIndex=5

log4j.appender.RollingFile.layout=org.apache.log4j.PatternLayout

#Print the date and time for RollingFile

log4j.appender.RollingFile.layout.ConversionPattern=%d [%t]

%-5p %c{1} - %m%n