JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy
  • Contact Us

Adapter Design Pattern

November 5, 2015 by Krishna Srinivasan Leave a Comment

In this tutorial I am going to explain about the adapter design pattern as part of the design patterns in Java series. Adapter design pattern is one of the structural design pattern because adapter design deals with how we make / structure an object. The primary problem this pattern trying to solve is to make it work two in-compatible interfaces. I think this gives the reason behind the term “adapter”.

Adapter Design Pattern

There are two types of adapter design patterns:

  1. Class Adapter : This type uses the Java inheritance to extend the class and then implement the adapter interface.
  2. Object Adapter : This uses the Java composition where Adapter contains the source object.

In the below example I have used both the types of adapter pattern for your reference. I have taken the simple example of PowerGrid where the voltage is coming with high volume, I am using an adapter to convert that into lower levels. Note that this is very simple and concept remains the same even if you implement in the real time.
PowerGrid.java

[code lang=”java”]
class PowerGrid {
public int getPower() {
return 1000;
}
}
[/code]

PowerAdapter.java

[code lang=”java”]
interface PowerAdapter {
int get10V();

int get50V();

int get100V();
}
[/code]

PowerAdapterClassImpl.java

[code lang=”java”]
class PowerAdapterClassImpl extends PowerGrid implements PowerAdapter {
@Override
public int get10V() {
return (getPower() / 100);
}

@Override
public int get50V() {
return (getPower() / 20);
}

@Override
public int get100V() {
return (getPower() / 10);
}
}
[/code]

PowerAdapterObjectImpl.java

[code lang=”java”]
class PowerAdapterObjectImpl implements PowerAdapter {
private PowerGrid grid;

@Override
public int get10V() {
return (grid.getPower() / 100);
}

@Override
public int get50V() {
return (grid.getPower() / 20);
}

@Override
public int get100V() {
return (grid.getPower() / 10);
}
}
[/code]

AdapterDesignPatternExample.java

[code lang=”java”]
public class AdapterDesignPatternExample {
public static void main(String args[]) {
PowerAdapter classAdapter = new PowerAdapterClassImpl();
System.out.println(classAdapter.get100V());
System.out.println(classAdapter.get50V());
System.out.println(classAdapter.get10V());

PowerAdapter objectAdapter = new PowerAdapterObjectImpl();
System.out.println(objectAdapter.get100V());
System.out.println(objectAdapter.get50V());
System.out.println(objectAdapter.get10V());

}
}
[/code]

I hope this tutorial would have provided you very basic example and illustration to implement the adapter design pattern. If you have any interesting example for the adapter design pattern, please share with us in the comments section.

Filed Under: Java Tagged With: Design Patterns

Builder Design Pattern

October 29, 2015 by Krishna Srinivasan Leave a Comment

In this tutorial I am going to explain about builder design pattern, this is one of the most widely used design pattern in Java. Builder design pattern comes under the creational design pattern since builder design pattern helps in creating an object using step-by-step approach.

Subscribe to our future updates.

Builder design pattern solves the problem of creating an object with lot of parameters and where some of the parameters are mandatory and some are optional. The builder design pattern is very much similar to abstract factory design pattern. The key difference between abstract factory pattern and builder pattern is that, where in abstract factory pattern factory methods are creating the objects. But in builder pattern, clear instructions are given to the builder to with step-by-step approach for creating the objects. That means you have complete control on what to be included and excluded in the object creation.

builder pattern

(image source)

Builder Design Pattern Example

Here is a very simple example that demonstrates how to use builder design pattern for creating the objects. In this builder design pattern example, I am creating a Family object using the FamilyBuilder. Here if you notice, FamilyBuilder class is static class with each method adding one propery to the object. Finally, a build that completes the object creation. I hope that this example helps you understand how to use builder design pattern. If you have any questions, please write it in the comments section.
Family.java

[code lang=”java”]
package net.javabeat.designpatterns.builderpattern;

import java.util.List;

public class Family {
private String familyName;
private String husband;
private String wife;
private int numberOfKids;
private List<String> kidsNames;
private int annualIncome;
private boolean isCarOwned;
private boolean isHouseOwned;
private String city;
private String country;

private Family(FamilyBuilder builder){
this.familyName = builder.familyName;
this.husband = builder.husband;
this.wife = builder.wife;
this.numberOfKids = builder.numberOfKids;
this.kidsNames = builder.kidsNames;
this.annualIncome = builder.annualIncome;
this.isCarOwned = builder.isCarOwned;
this.isHouseOwned = builder.isHouseOwned;
this.city = builder.city;
this.country = builder.country;
}
//All getter, and NO setter to provide immutability
public String getFamilyName() {
return familyName;
}

public String getHusband() {
return husband;
}

public String getWife() {
return wife;
}

public int getNumberOfKids() {
return numberOfKids;
}

public List<String> getKidsNames() {
return kidsNames;
}

public int getAnnualIncome() {
return annualIncome;
}

public boolean isCarOwned() {
return isCarOwned;
}

public boolean isHouseOwned() {
return isHouseOwned;
}

public String getCity() {
return city;
}

public String getCountry() {
return country;
}

public String toString(){
StringBuilder result = new StringBuilder();
result.append("Family Name : "+this.familyName);
result.append("\nHusband Name : "+this.husband);
result.append("\nWife Name : "+this.wife);
result.append("\nNumber of Kids : "+this.numberOfKids);
result.append("\nKids Names : "+this.kidsNames);
result.append("\nAnnual Income : "+this.annualIncome);
result.append("\nIs Own Car : "+this.isCarOwned);
result.append("\nIs Own House : "+this.isHouseOwned);
result.append("\nCity : "+this.city);
result.append("\nCountry : "+this.country);
return result.toString();
}

public static class FamilyBuilder{
private String familyName;
private String husband;
private String wife;
private int numberOfKids;
private List<String> kidsNames;
private int annualIncome;
private boolean isCarOwned;
private boolean isHouseOwned;
private String city;
private String country;
public FamilyBuilder(String familyName){
this.familyName = familyName;
}
FamilyBuilder husband(String husband){
this.husband = husband;
return this;
}
FamilyBuilder wife(String wife){
this.wife = wife;
return this;
}
FamilyBuilder kids(int kids){
this.numberOfKids = kids;
return this;
}
FamilyBuilder kidsNames(List kidsNames){
this.kidsNames = kidsNames;
return this;
}
FamilyBuilder annualIncome(int annualIncome){
this.annualIncome = annualIncome;
return this;
}
FamilyBuilder isCarOwned(boolean isCarOwned){
this.isCarOwned = isCarOwned;
return this;
}
FamilyBuilder isHouseOwned(boolean isHouseOwned){
this.isHouseOwned = isHouseOwned;
return this;
}
FamilyBuilder city(String city){
this.city = city;
return this;
}
FamilyBuilder country(String country){
this.country = country;
return this;
}
//Return the finally construcuted Family object
public Family build() {
Family family = new Family(this);
return family;
}
}
}
[/code]

BuilderDesignPatternExample.java

[code lang=”java”]
package net.javabeat.designpatterns.builderpattern;

import java.util.ArrayList;
import java.util.List;

public class BuilderDesignPatternExample {

public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("Nancy");
Family family = new Family.FamilyBuilder("Happy Family").husband("John").wife("Marry").
kids(1).kidsNames(list).annualIncome(100000).isCarOwned(true).
isHouseOwned(true).city("NewYork").country("USA").build();
System.out.println(family);
}
}
[/code]

Filed Under: Java Tagged With: Design Patterns

State Design Pattern In Java

April 28, 2014 by Krishna Srinivasan Leave a Comment

This tutorial explains the state design pattern with a simple example program. State design pattern is very similar to the Strategy pattern, the only difference is that state design pattern maintains the state of the context where as strategy pattern passes the context and execute the specific strategy.

The state design pattern is very useful in the scenarios where sequence of actions are taken with the pre-defined order. A perfect example is the lifecycle methods executed in a framework. Each phase is invoked one after the another by looking at the current phase of the context. I have used the lifecycle example for explaining the state design pattern example.

  • State operation will be declared as interface. Actual implementations will have the specific states with reference to the next state.
  • State context is where state instantiated with the initial state. State contact will declare a constructor to initialize state.
  • When you invoke the operation, it will keep moving to the different states for each execution.

State.java

[code lang=”java”]
package javabeat.net.pattern;

public interface State {
public void execute(StateContext context);
}
[/code]

StateOne.java

[code lang=”java”]
package javabeat.net.pattern;

public class StateOne implements State{
public void execute(StateContext context){
System.out.println("State One Executed!!");
context.setState(new StateTwo());
}
}
[/code]

StateTwo.java

[code lang=”java”]
package javabeat.net.pattern;

public class StateTwo implements State {
public void execute(StateContext context){
System.out.println("State Two Executed!!");
context.setState(new StateThree());
}
}
[/code]

StateThree.java

[code lang=”java”]
package javabeat.net.pattern;

public class StateThree implements State{
public void execute(StateContext context){
System.out.println("State Three Executed!!");
}
}
[/code]

StateContext.java

[code lang=”java”]
package javabeat.net.pattern;

public class StateContext {
State state = null;
public StateContext(State state){
this.setState(new StateOne());
}
public void setState(State state){
this.state = state;
}

public void runLifeCycle(){
state.execute(this);
}
}
[/code]

StatePatternExample.java

[code lang=”java”]
package javabeat.net.pattern;

/**
* State design pattern example
*
* @author Krishna
*
*/
public class StatePatternExample {
public static void main(String[] args) {
//Create state context
StateContext context = new StateContext(new StateOne());

//Invoke operation from state context
context.runLifeCycle();
context.runLifeCycle();
context.runLifeCycle();
}
}
[/code]

Output…

[code]
State One Executed!!
State Two Executed!!
State Three Executed!!
[/code]

  • We have implemented State interface to execute each state.
  • StateOne, StateTwo and StateThree are the three states we have implemented using the State interface.
  • StateContext is the actual context where the state would be invoked. You can consider this as your main application.

You can run the StatePatternExample class to test the State Design Pattern.

Filed Under: Java Tagged With: Design Patterns

Design Patterns in Java

September 25, 2013 by Manisha Patil Leave a Comment

In developing a system, it is expected that some requirements are guaranteed, for example, performance, robustness, understanding, ease of reuse, modification, and use. The Design Patterns were created by the architect Christopher Alexander , in the 1970s. During this period the architect wrote two books: “Pattern Language” and “Timeless Way of Building“. These books were an example of how Christopher thought in order to document these patterns.

If you are interested in receiving updates, please subscribe our newsletter.

In 1995, the professionals: Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides , wrote and released the book called “Design Patterns: Elements of Reusable Object-Oriented Software”, which shows the details of the 23 Design Patterns. For this achievement, the professionals were baptized with the name “Gang of Four” (Gang of Four or GoF).

Design Patterns in Java

The goal of design patterns are:

  • Reusable components that make it easy to standardize.
  • Enabling agile solutions for recurring problems in developing the system.

There are two design patterns known to software engineering. Those are:

  • Standard GoF (Gang of Four) patterns
  • GRASP (General Responsibility Assignment Software Patterns).

History of Design Patterns

GRASP Design Patterns

  • Design Pattern Interview Questions

These patterns consists of guidelines for assigning responsibility to classes and objects in object-oriented design. The different patterns and principles and standards used in GRASP  design patterns are:

  • Specialist in information
  • Creator
  • Controller
  • Weak coupling
  • High Cohesion
  • Polymorphism
  • Pure Fabrication
  • Indirection
  • Protected Variations

GoF Design Patterns

These patterns consist of three groups as shown below:

  • Creational Patterns
    • Factory Method
    • Abstract Factory
    • Singleton, Builder
    • Prototype
  • Structural Patterns
    • Adapter
    • Bridge
    • Composite
    • Decorator
    • Facade
    • Flyweight
    • Proxy
  • Behavioral Patterns
    • Chain of Responsibility
    • Command
    • Interpreter
    • Iterator
    • Mediator
    • Memento
    • Observer
    • State
    • Strategy
    • Template
    • Method
    • Visitor.

GoF Design Patterns of Creation

Creational Design Patterns

The patterns of this type require a treatment of how objects (classes) are created to meet the diverse needs. In Java, objects are instantiated through their builders, but the use of them is limited when:

  • The code that references the creation of an object needs to know the builders of it, it increases the coupling of classes.
  • The object can not be created partially.
  • The builder can not control the number of instances in the present application.

Illustrative pattern

Figure 1 : Illustration of the figurative Pattern GoF Creation

  • Factory Method : This standard defines an interface for creating an object, letting the subclasses remain responsible for deciding which class to instantiate.
  • Abstract Factory : Allows you to draw an interface for creating families of related objects or interdependent, not specifying their concrete classes. These standards can be created using concrete factories, which are responsible for the creation of new objects to meet customer needs. Therefore, this practice helps to exclude the dependency between the client and the class of objects used by the client.
  • Singleton : Used when desired, that a class has only one instance of the application. Below are some aspects that should be taken care of when creating this pattern:
  • The class is final, it does not allow the creation of subclasses of the class itself.
  • Access is granted through the method that returns a single instance of the class, or is creating one, if it has not been created.
  • Builder : Provides a generic interface for the incremental construction of aggregations. This pattern hides the details of how the components are created, composed and represented.
  • Prototype : Defines the types of objects to be created from an instance that serves as a prototype. New objects are created based on this prototype.

GoF Structural Design Patterns

Structural Design Pattern in Java

This standard describes the following aspects: preparation, organization and association between objects and classes / interfaces. Allows to combine objects into more complex structures, or describe how the classes are inherited or composed from other.

gofstructure

Figure 2 : Illustration GoF Structural Pattern

  • Adapter : The action of this pattern converts the interface of a class into another, expected by the client object. Through this conversion, allows classes with incompatible interfaces, able to be adapted so that other objects can work together.
  • Bridge : This pattern separates an abstraction from its implementation, allowing both to work independently, and establishes a bridge between them.
  • Composite : Consisting of objects aggregation trees. Aggregate objects are treated as a single object.
  • Decorator : This standard seeks to offer a flexible alternative to extension object dynamic new features, without the use of inheritance. An example is the use of the scroll bar that can be incorporated dynamically to a window, text box or web page.
  • Facade : Provides a unified interface to a set of objects that consists of a subsystem, defining a high-level interface that facilitates the use.
  • Flyweight : Use sharing to support efficiently to a large number of objects with high level of granularity. This pattern creates models for each object, which concentrates all the common features of an object.
  • Proxy : Allows access is controlled by another object, which acts as a substitute. Generally used in aspect-oriented programming, aiming to help sort, wrap, modularizing methods and organize code according to importance.

GoF Behavioural Patterns

Behavioural Design Pattern in Java

These patterns show the process of how objects or classes communicate. In general, look for a loose coupling between objects, although the communication that exists between them.

gofbehaviour

Figure 3 : Illustration of GoF Behavioral Pattern

  • Chain of Responsibility : This design pattern consists of a source of command objects and a series of processing objects. Each processing object contains logic that defines the types of command objects that it can handle; the rest are passed to the next processing object in the chain. A mechanism also exists for adding new processing objects to the end of this chain.
  • Command : encapsulates a message or request as an object, so that it can set parameters with different messaging clients.
  • Interpreter : Are representations and abstractions for grammars for parsing, being used for more language definition.
  • Iterator : Used to provide a way to access elements of a collection of objects sequentially without exposing the internal structures.
  • Mediator : This pattern defines an object that encapsulates how a set of objects interact. This pattern is considered to be a behavioral pattern due to the way it can alter the program’s running behavior.
  • Memento : Works as a “snapshot”, it captures and externalizes the internal state of an object without violating encapsulation, allowing the object can be restored to this state in the future. One example is operations that need to be reversed, so that the previous state of the object is then restored.
  • Observer : Used to synchronize, coordinate and maintain consistency between related objects which have one to many dependency between objects, ie, when the state of an object changes, all dependents are notified and updated automatically.
  • State : This patter encapsulates varying behavior for the same routine based on an object’s state object. This can be a cleaner way for an object to change its behavior at runtime without resorting to large monolithic conditional statements.
  • Strategy : Defines a new set of algorithms without changing the classes of the elements on which it operates.
  • Template Method : This pattern defines the program skeleton of an algorithm in a method, called template method, which defers some steps to subclasses. It lets one redefine certain steps of an algorithm without changing the algorithm’s structure.
  • Visitor : It is a way of separating an algorithm from an object structure on which it operates. A practical result of this separation is the ability to add new operations to existing object structures without modifying those structures. It is one way to follow the open/closed principle.

Summary

  • Design pattern interview questions

In this article, we saw types of design patterns GoF patterns and GRASP. We also saw further categorization in each of these patterns. This article aims at giving a basic knowledge of design patterns. With this basic knowledge you can proceed to understand each of these patterns better and implement in your day to day software applications.

Filed Under: Java Tagged With: Design Patterns

Lazy Initialization, Singleton Pattern and Double Checked locking

July 24, 2012 by Mohamed Sanaulla Leave a Comment

Lazy Initialization

Lazy Initialization is a technique where one postpones the instantiation of a object until its first use. In other words the instance of a class is created when its required to be used for the first time. The idea behind this is to avoid unnecessary instance creation. But there are concerns related to using such approaches in a concurrent scenario. But before that lets see how lazy initialization looks:

also read:

  • Design Pattern Interview Questions
  • Factory Design Pattern
  • State design pattern

[code lang=”java”]
class ResourceManager{
private Resource resource;
public Resource getResource(){
if ( resource == null ){
resource = new Resource();
}
return resource;
}
}
[/code]
When the above code is executed in a multi threaded program the concern that immediately comes to the mind is the “Race condition”.
Thread A would check that resource == null so it goes inside to create the instance but might go into Runnable status before it creates the Resource instance.
Thread B also checks that resource == null and it goes ahead, creates the instance and uses it for its operations.
Thread A comes back to running status and it also continues to create its own instance and start using it.

Now in the above case suppose we wanted both Thread A and Thread B to work on the same instance, but due to the race condition they would work on different instances. If the Resource instances has state information associated with it then it because a critical problem. Lets stop here and then see how Singleton is related to this.

Singleton

Singleton is one of the Creational Design Patterns discussed in the GoF Design Patterns. The main idea behind the Singleton pattern is to control the creation of objects for a given class such that at any time there’s only one instance of that particular class. So lets see how we can implement the Singleton pattern:

[code lang=”java”]
class Resource{
private static Resource instance;
public static Resource getInstance(){
if ( instance == null){
instance = new Resource();
}
return instance;
}
}
[/code]
where in the above example Resource is a singleton. This is very similar to the concept of lazy initialization and this as well suffers from the issues seen while using this is a multi threaded environment/program.

Double Checked Locking

One way to solve the problem with Lazy initialization and singleton in a multi threaded program is to declare the getInstance() or getResource() method as synchronized. But its a huge overhead because everytime the method is invoked it has to go through the process of waiting for the lock and then obtaining the lock and its unnecessary because its only once that the instance is created and all subsequent invocations would just return that instance.

To work around this issue, Double Checked Locking is the pattern used. In this approach the methods are not synchronized instead the instance creation code is put in a synchronized block. Let me show an example:
[code lang=”java”]
class Resource{
private static Resource instance;
public static Resource getInstance(){
if ( instance == null ){
synchronized(Resource.class){
if ( instance == null ){
instance = new Resource();
}
}/end of synchronized block.
}
return instance;
}
}
[/code]
In the above code there are two null checks- one outside the synchronized block and one within it. The synchronized block is executed at most once and any other thread trying to get instance would have to wait until the instantiation to complete.

The above approach also has some issues. The initialization of an object and the creation of instance of that class are 2 different operations. Once the instance of the class has been created that instance is then used to initialize the values of its state either with default values or some user defined values. Now between these 2 operations another thread might invoke the method to get the instance and sees that the instance is already not null and then proceeds with using that instance. Though its the correct instance we wanted the thread to use but that instance hasn’t been initialized yet. This issue is called as Unsafe Publication. Java Concurrency in Practice book has a really good chapter on Java Memory Model and issues related to Safe Publication and Unsafe Publication of instances.

Lazy Initialization holder class idiom

One can read about this Lazy Initialization holder class Idiom in the interview with Joshua Bloch here. It has been covered in Effective Java by Joshua Bloch and also in Java Concurrency in Practice. Let me just share that idea here:
[code lang=”java”]
class Resource{
private static class ResourceHolder{
static final Resource instance = new Resource();
}
public static Resource getInstance(){
return ResourceHolder.instance;
}
}
[/code]
This takes advantage of:

  • Eager Initialization
  • Class not initialized unless its used/loaded by the class loader the first time its used.

Another interesting discussion related to this on JavaRanch.

Filed Under: Java Tagged With: Design Patterns

Design Patterns Interview Questions

February 13, 2009 by Krishna Srinivasan Leave a Comment

1) What is a software design pattern?

A design pattern is a solution to a general software problem within a particular context.

  • Context : A recurring set of situations where the pattern applies.
  • Problem : A system of forces (goals and constraints) that occur repeatedly in this context.
  • Solution : A description of communicating objects and classes (collaboration) that can be applied to resolve those forces.

Design patterns capture solutions that have evolved over time as developers strive for greater flexibility in their software. Whereas class libraries are reusable source code, and components are reusable packaged objects, patterns are generic, reusable design descriptions that are customized to solve a specific problem. The study of design patterns provides a common vocabulary for communication and documentation, and it provides a framework for evolution and improvement of existing patterns.

2) Why is the study of patterns important?

As initial software designs are implemented and deployed, programmers often discover improvements which make the designs more adaptable to change. Design patterns capture solutions that have evolved over time as developers strive for greater flexibility in their software, and they document the solutions in a way which facilitates their reuse in other, possibly unrelated systems. Design patterns allow us to reuse the knowledge of experienced software designers.

Moreover, the study of design patterns provides a common vocabulary for communication and documentation, and it provides a framework for evolution and improvement of existing patterns. As an analogy, consider that during a discussion among programmers, the words stack and tree can be used freely without explanation. Software developers understand fundamental data structures such as a stack because these data structures are well-documented in textbooks and are taught in computer science courses. The study of design patterns will have a similar (but more profound) effect by allowing designers to say composite pattern or observer pattern in a particular design context, without having to describe all classes, relationships, and collaborations which make up the pattern. Patterns raise the level of abstraction when discussing and documenting software designs.

3) How do I document a design pattern?

A pattern description must address the following major points:

  • Pattern Name and Classification : A short, meaningful name for the pattern, usually only one or two words. Names provide a vocabulary for patterns, and they have implied semantics choose names carefully. Following the GoF book, we can also group patterns into higher level classifications such as creational, structural, and behavioral patterns.
  • Problem : A general description of the problem context and the goals and constraints that occur repeatedly in that context. A concrete motivational scenario can be used to help describe the problem. The problem description should provide guidance to assist others in recognizing situations where the pattern can be applied.
  • Solution : The classes and/or objects that participate in the design pattern, their structure (e.g., in terms of a UML class diagram), their responsibilities, and their collaborations. The solution provides an abstract description that can be applied in many different situations. Sample Code in an object-oriented language can be used to illustrate a concrete realization of the pattern.
  • Consequences : A discussion of the results and tradeoffs of applying the pattern. Variations and language-dependent alternatives should also be addressed.
  • Known Uses : Examples of the pattern in real systems. Look for applications of the pattern in language libraries and frameworks, published system descriptions, text books, etc. Not every good solution represents a pattern. A general rule of thumb is that a candidate pattern (also called a proto-pattern) should be discovered in a minimum of three existing systems before it can rightfully be called a pattern.

The following quote by Robert Martin highlights the importance of providing pattern descriptions: The revolutionary concept of the GoF book is not the fact that there are patterns; it is the way in which those patterns are documented. Prior to the GoF book, the only good way to learn patterns was to discover them in design documentation, or (more probably) code.

4) Where can I learn more about design patterns?

The best place to start is the seminal work by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (collectively known as the Gang of Four or simply GoF) entitled Design Patterns: Elements of Reusable Object-Oriented Software (Addison-Wesley, 1995).

Warning: This book is not light reading. From the Preface: Don’t worry if you don’t understand this book completely on the first reading. We didn’t understand it all on the first writing.

It is, however, a book which wears well over time, and it is definitely worth the effort required to work through it.

5) What is an example of a design pattern?

Following the lead of the Gang of Four (GoF), design pattern descriptions usually contain multiple sections including

  • Intent
  • Motivation
  • Applicability
  • Structure
  • Partcipants
  • Collaborations
  • Consequences
  • Implementation
  • Sample Code
  • Known Issues
  • Related Patterns

A complete discussion of even a small pattern is beyond the scope of a simple FAQ entry, but it is possible to get the idea by examining an abbreviated discussion of one of the simplest and most easily understood patterns. Consider the Singleton pattern, whose intent reads as follows:

Intent: Ensure that a class has one instance, and provide a global point of access to it.

Almost every programmer has encountered this problem and formulated an approach for solving it in a general way – some solutions are better than others. The solution offered by the GoF would look something like the following when coded in Java.

[code lang=”java”]
public class Singleton {
private static Singleton instance = null;
public static Singleton getInstance() {
if (instance == null)
instance = new Singleton();
return instance;
}
protected Singleton() { … }
// possibly another constructor form
public void someMethod() { … }
//… other methods }

[/code]

The programmer would access the single instance of this class by writing something similar to

[code lang=”java”]
Singleton.getInstance().someMethod()
[/code]

or, similar to

[code lang=”java”]
Singleton s = Singleton.getInstance();
s.method1(); …
s.method2(); …
[/code]

6) Calendar is an abstract class. The getInstance() method tries to instantiate GregorianCalendar() i.e., parent instantiating a derived class. This looks Non-OO? Ex: Calendar a=Calendar.getInstance(); Can somebody explain why is it so?

The Calender class is an abstact class, true, however,the point you missed is that the getInstance() returns the Calendar using the default timezone and locale. , in your case, the GregorianCalender a class that IS a Calender (a Suzuki IS a car, a 747 IS a plane..the standard OO terminology. So what you get is a class that does some specialized work based on the default locale. Other methods

[code lang=”java”]
public static synchronized Calendar
getInstance(TimeZone zone,Locale aLocale)
public static synchronized Calendar
getInstance(TimeZone zone)
[/code]

return Calenders for specific timezones and locales. The closest parallel is possibly the Factory Method design pattern.

7) What major patterns do the Java APIs utilize?

Design patterns are used and supported extensively throughout the Java APIs. Here are some examples:

  • The Model-View-Controller design pattern is used extensively throughout the Swing API.
  • The getInstance() method in java.util.Calendar is an example of a simple form of the Factory Method design pattern.
  • The classes java.lang.System and java.sql.DriverManager are examples of the Singleton pattern, although they are not implemented using the approach recommended in the GoF book but with static methods.
  • The Prototype pattern is supported in Java through the clone() method defined in class Object and the use of java.lang.Cloneable interface to grant permission for cloning.
  • The Java Swing classes support the Command pattern by providing an Action interface and an AbstractAction class.
  • The Java 1.1 event model is based on the observer pattern. In addition, the interface java.util.Observable and the class java.util.Observer provide support for this pattern.
  • The Adapter pattern is used extensively by the adapter classes in java.awt.event.
  • The Proxy pattern is used extensively in the implementation of Java’s Remote Method Invocation (RMI) and Interface Definition Language (IDL) features.
  • The structure of Component and Container classes in java.awt provide a good example of the Composite pattern.
  • The Bridge pattern can be found in the separation of the components in java.awt (e.g., Button and List), and their counterparts in java.awt.peer.

8)How can I make sure at most one instance of my class is ever created?

This is an instance where the Singleton design pattern would be used. You need to make the constructor private (so nobody can create an instance) and provide a static method to get the sole instance, where the first time the instance is retrieved it is created:

[code lang=”java”]
public class Mine {
private static Mine singleton; private Mine() { }
public static synchronized Mine getInstance() {
if (singleton == null) {
singleton = new Mine();
} return singleton;
}
// other stuff… }
[/code]

9) When would I use the delegation pattern instead of inheritence to extend a class’s behavior?

Both delegation and inheritance are important concepts in object-oriented software design, but not everyone would label them as patterns. In particular, the seminal book on design patterns by the Gang of Four contains a discussion of inheritance and delegation, but the authors do not treat these topics as specific patterns. It is reasonable to think of them as design concepts which are more general than specific design patterns.

Inheritance is a relationship between two classes where one class, called a subclass in this context, inherits the attributes and operations of another class, called its superclass. Inheritance can be a powerful design/reuse technique, especially when it is used in the context of the Liskov Substitution Principle. The primary advantages of inheritance are

  • it is directly supported by object-oriented languages,
  • and it provides the context for polymorphism in strongly-typed object-oriented languages such as C++ and Java.

But since the inheritance relationship is defined at compile-time, a class can’t change its superclass dynamically during program execution. Moreover, modifications to a superclass automatically propagate to the subclass, providing a two-edged sword for software maintenance and reuse. In summary, inheritance creates a strong, static coupling between a superclass and its subclasses.

Delegation can be viewed as a relationship between objects where one object forwards certain method calls to another object, called its delegate. Delegation can also a powerful design/reuse technique. The primary advantage of delegation is run-time flexibility the delegate can easily be changed at run-time. But unlike inheritance, delegation is not directly supported by most popular object-oriented languages, and it doesn’t facilitate dynamic polymorphism.

As a simple example, consider the relationship between a Rectangle class and a Window class. With inheritance, a Window class would inherit its rectangular properties from class Rectangle. With delegation, a Window object would maintain a reference or pointer to a Rectangle object, and calls to rectangle-like methods of the Window object would be delegated to corresponding methods of the Rectangle object.

Now let’s consider a slightly more complex example. Suppose employees can classified based on how they are paid; e.g., hourly or salaried. Using inheritance, we might design three classes: an Employee class which encapsulates the functionality common to all employees, and two subclasses HourlyEmployee and SalariedEmployee which encapsulates pay-specific details. While this design might be suitable for some applications, we would encounter problems in a scenario where a person changes, say from hourly to salaried. The class of an object and the inheritance relationship are both static, and objects can’t change their class easily (but see the State pattern for tips on how to fake it).

A more flexible design would involve delegation an Employee object could delegate pay-related method calls to an object whose responsibilities focused solely on how the employee is paid. In fact, we might still use inheritance here in a slightly different manner by creating an abstract class (or interface) called PayClassification with two subclasses HourlyPayClassification and SalariedPayClassification which implement classification-specific computations. Using delegation as shown, it would be much easier to change the pay classification of an existing Employee object.

This second example illustrates an important point: In implementing delegation, we often want the capability to replace the delegate with another object, possibly of a different class. Therefore delegation will often use inheritance and polymorphism, with classes of potential delegates being subclasses of an abstract class which encapsulates general delegate responsibilities.

One final point. Sometimes, the choice between delegation and inheritance is driven by external factors such as programming language support for multiple inheritance or design constraints requiring polymorphism. Consider threads in Java. You can associate a class with a thread in one of two ways: either by extending (inheriting) directly from class Thread, or by implementing the Runnable interface and then delegating to a Thread object. Often the approach taken is based on the restriction in Java that a class can only extend one class (i.e., Java does not support multiple inheritance). If the class you want to associate with a thread already extends some other class in the design, then you would have to use delegation; otherwise, extending class Thread would usually be the simpler approach.

10) Which patterns were used by Oracle in designing the Enterprise JavaBeans model?

Many design patterns were used in EJB, and some of them are clearly identifiable by their naming convention. Here are several:

Factory Method: Define a interface for creating classes, let a subclass (or a helper class) decide which class to instantiate. This is used in EJB creation model. EJBHome defines an interface for creating the EJBObject implementations. They are actually created by a generated container class. See InitialContextFactory interface that returns an InitialContext based on a properties hashtable.

Singleton: Ensure a class has only one instance, and provide a global point of access to it. There are many such classes. One example is javax.naming.NamingManager

Abstract Factory: Provide an interface for creating families of relegated or dependent objects without specifying their concrete classes. We have interfaces called InitialContext, InitialContextFactory. InitialContextFactory has methods to get InitialContext.

Builder: Separate the construction of a complex factory from its representation so that the same construction process can create different representations.
InitialContextFactoryBuilder can create a InitialContextFactory.

Adapter: Convert the interface of a class into another interface clients expect.In the EJB implementation model, we implement an EJB in a class that extends SessionBean or a EntityBean. We don’t directly implement the EJBObject/home interfaces. EJB container generates a class that adapts the EJBObject interface by forwarding the calls to the enterprise bean class and provides declarative transaction, persistence support.

Proxy: Provide a surrogate for other object to control access to it. We have remote RMI-CORBA proxies for the EJB’s.

Memento: Without violating encapsulation, capture and externalize an object’s internal state so that the object can be restored to this state later. Certainly this pattern is used in activating/passivating the enterprise beans by the container/server.

11) What is an analysis pattern?

An analysis pattern is a software pattern not related to a language or implementation problem, but to a business domain, such as accounting or health care. For example, in health care, the patient visit activity would be subject to a number of patterns. There is a good overview from an OOPSLA ’96 presentation at http://www.jeffsutherland.org/oopsla96/fowler.html. A good text would be: Martin Fowler’s Martin Analysis Patterns : Reusable Object Models, ISBN: 0201895420, published by Addison-Wesley. In summary, analysis patterns are useful for discovering and capturing business processes.

12) What are the differences between analysis patterns and design patterns?

Analysis pattern are for domain architecture, and design pattern are for implementation mechanism for some aspect of the domain architecture. In brief, analysis pattern are more high level and more (end-user) functional oriented.

13) How does Extreme Programming (XP) fit with patterns?

Extreme Programming has a large emphasis on the concept of refactoring: Writing code once and only once. Patterns, particularly the structural patterns mentioned by the Gang of Four, can give good pointers about how to acheive that goal. (XP states when and where factoring should happen, patterns can show you how.)

14) What is the disadvantage of using the Singleton pattern? It is enticing to use this pattern for all the classes as it makes it easy to get the reference of the singleton object.

The intent of the Singleton pattern is to ensure a class has only one instance and to provide a global point of access to it. True, the second part about providing a global point of access is enticing, but the primary disadvantage of using the Singleton pattern for all classes is related to the first part of the intent; i.e., that it allows only one instance of the class. For most classes in an application, you will need to create multiple instances. What purpose would a Customer class serve if you could create only one Customer object?

15) How do you write a Thread-Safe Singleton?

I have written plenty of non-thread-safe Singletons but it wasn’t until recently when I tracked it down that I realized that thread-safety could be a big problem.

The problem is that in the typical Singleton implementation (at least the ones I’ve seen) there is the ability to create multiple versions of the single instance I know, But How?.

Well, in the getInstance() call the instance is checked for null, and then immediately constructed if it is null, and then the instance is returned.

The problem is that the thread (Ta) making the call could swap-out immediately after checking for a null. A subsequent thread (Tb) could then make a call to get the instance and construct an instance of the Singleton. When the original thread (Ta) is then swapped back in, it would construct and return a completely separate object. BAD KITTY!

The following code snippet shows an example of a thread-safe Singleton.

[code lang=”java”]
package com.jgk.patterns.singleton;
public class JGKSingleton {
/* Here is the instance of the Singleton */
private static JGKSingleton instance_;
/* Need the following object to synchronize */
/* a block */
private static Object syncObject_;
/* Prevent direct access to the constructor
private JGKSingleton() { super(); }

public static JGKSingleton getInstance() {
/* in a non-thread-safe version of a Singleton */
/* the following line could be executed, and the */
/* thread could be immediately swapped out */
if (instance_ == null) {
synchronized(syncObject_) {
if (instance_ == null) {
instance_ = new JGKSingleton();
}
}
}
return instance_;
}
}

[/code]

16) What is the Reactor pattern?

The new book Pattern-oriented Software Architecture Volume 2? ISBN 0471606952 has a chapter on the Reactor pattern. It falls under the general category of “Event Handling Patterns. To quote the leading bit of the chapter, The Reactor architectural pattern allows event-driven applications to demultiplex and dispatch service requests that are delivered to an application from one or more clients. It is used in a synchronous manner, so that if the callback you delegate the event to takes a while to complete you will run into problems with scalability.

17) What are Process Patterns?

Basically process patterns define a collection of best practices, techniques, methods for developing object-oriented software. A good reference site is by Scott Ambler. He also has two books on the topic plus a white paper on the subject you can download. http://www.ambysoft.com/processPatternsPage.html.

18) How and where did the concept of design patterns get started?

Work on patterns has been influenced by the works of Christopher Alexander who published on topics related to urban planning and building architecture in the late 1970s. The history of patterns for software design began in the late 1980s and reached an important milestone with the publishing of the first book fully dedicated to this subject by the Gang of Four, Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides, Design Patterns Elements of Reusable Object-Oriented Software). In conjunction, the emergence of object-oriented software development fostered the work on other topics related to design patterns such as application frameworks, analysis patterns, language idioms, and so on.

19) Where can I find good examples of the Prototype pattern?

The prototype pattern is actually quite simple to implement in Java.

Recall that the idea of prototype is that you are passed an object and use that object as a template to create a new object. Because you might not know the implementation details of the object, you cannot create a new instance of the object and copy all of its data. (Some of the data may not be accessible via methods). So you ask the object itself to give you a copy of itself.

Java provides a simple interface named Cloneable that provides an implementation of the Prototype pattern. If you have an object that is Cloneable, you can call its clone() method to create a new instance of the object with the same values.

The trick here is that you must override the clone() method to increase its visibility, and just call super.clone(). This is because the implementation of clone(), defined in java.lang.object, is protected. For example:

[code lang=”java”]
public class CopyMe implements Cloneable {
public Object clone() {
return super.clone();
}
}
[/code]

Note that Cloneable is an empty interface! It merely acts as a tag to state that you really want instance of the class to be cloned. If you don’t implement Cloneable, the super.clone() implementation will throw a CloneNotSupportedException.

The Object implementation of clone() performs a shallow copy of the object in question. That is, it copies the values of the fields in the object, but not any actual objects that may be pointed to. In other words, the new object will point to the same objects the old object pointed to.

As an example of using the cloning:

[code lang=”java”]
CopyMe thing = new Copyme();
CopyMe anotherThing = (Copyme)thing.clone();
[/code]

This example is pretty trivial, but the real power comes when you don’t know what you’re actually cloning. For example, suppose you define an interface that represents a customer:

[code lang=”java”]
public interface Customer extends Cloneable {
public Object clone();
// require making it public! public String getName();
public void setName(String name); … }
[/code]

You might have several different implementations of this interface, possibly storing data in a file, database, or using EJB Entity beans. If a shallow copy of the data is sufficient to represent a copy of the object, Java’s clone() method works great.

You might have a method that needs to make a copy of the data to store it in a Hashtable, for example:

[code lang=”java”]
public void storeCustomer(Customer customer) {
Customer copy = (Customer)customer.clone();
dataStore.put(copy);
}
[/code]

Note that this method knows nothing about what type of customer we’re getting. This pattern will work for any actual type of Customer, no matter how the data is stored. For example:

[code lang=”java”]
FileBasedCustomer c1 = new FileBasedCustomer(…);
RDBMSBasedCustomer c2 = new RDBMSBasedCustomer(…);
EJBBasedCustomer c3 = new EJBBasedCustomer(…);
manager.storeCustomer(c1);
manager.storeCustomer(c2);
manager.storeCustomer(c3);
[/code]

20) What are Anti-Patterns?

There isn’t really a clean-cut definition out there just yet, unlike Design Patterns. Basically, as Design Patterns (and more particularly, Process Patterns) try to codify a standard vocabulary for working solutions to problems that reappear frequently, Anti-Patterns represent an effort to define and classify reoccuring non-solutions, i.e., things that lots of projects do that fail to yield a solution, or actually prevent a project from working or being finished.

The most basic example I can think of is The Hammer, inspired by the old addage, If your only tool is a hammer, everything looks like a nail (or the variation, If your only tool is a hammer, everything looks like your left thumb.Hammer describes a regular, reoccuring problem in inexperienced engineers (particularly those who’ve only used one language for the bulk of their carreer so far), that of trying to force-feed all problems into the solutions they already know.

21) What patterns are particularly useful in building networked applications?

I suggest starting with Pattern-Oriented Software Architecture: Patterns for Concurrent and Networked Objects (POSA2). POSA2 specifically brings together 17 interrelated patterns addressing Service Access and Configuration, Event Handling, Synchronization, and Concurrency. The patterns and many of the examples in POSA2 come primarily from the design and implementation of the ACE framework.

22) Are there any good Java-specific patterns books available?

  • Head First Design Patterns by Kathy Sierra, Eric Freeman, Elisabeth Freeman, Bert Bates
  • Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides

23) What are Collaboration Patterns?

Collaboration Patterns are repeatable techniques used by teams of people to help them work together (collaborate). Ellen Gottesdiener of EBG Consulting has created these patterns in order to help facilitate good teamwork. These patterns really have nothing to do with object-oriented development or Java, besides the fact that they can help with requirements gathering or CRC design sessions.
In a nutshell, Collaboration Patterns are techniques to help make meetings useful.

24) Is it correct from a design point of view to make an object both an Observer and Observable at the same time?

Yes, and this can be the preferred pattern in some cases.

For example, suppose you were writing a supply chain management system for a retail chain. Each store object in your system generates item-sold events; when the chain generates enough of these for a particular product, a buyer object generates a purchase order for more of the product. However, the buyer object has no particular interest in individual item sold events. Instead, the buyer (Observer) registers to receive out-of-stock events from the warehouse (Observable); the warehouse, as Observer, registers with the individual stores (Observables) to receive item-sold events. Thus, the warehouse is both Observer and Observable. (Please note that this is a synthetic example, and probably not the way to organize a supply chain.)

Another reason to use one or more central Observer-Observable object in between ultimate Observers and Observables is to fully decouple the two. In some cases, Observer and Observable may exist on different machines, and may rely on the central Observer-Observable to hide this complication.

A good source for more details is the Publisher-Subscriber section of Buschmann et al., Pattern-Oriented Software Architecture: A System of Patterns.

25) How can I maintain a single instance of an object in an applet?

In start(), instead of always creating a new object, return the existing one if it exists or create a new one if it doesn’t.

26) What is the best way to generate a universally unique object ID? Do I need to use an external resource like a file or database, or can I do it all in memory?

I need to generate unique id’s that will be used for node ‘ID’ attribute values within XML documents. This id must be unique system-wide. The generator must be available to a number of servlets that add various node structures to my XML docs as a service. What is the best way to tackle this? The ‘possible’ ways I can see:

  • Keep the maximum ID value in a flat-file where the service would read it upon start-up and increment it. Upon shutdown or failure, it would write the latest max id to the file.
  • Calculate the max id by searching the XML itself. This will be tougher since XML requires an alpha-numeric value (not strictly numeric).
  • Use a database (MySQL) with a two-field table where one field is the incremental counter.

I just have this feeling that none of the above are the most efficient ways of doing this.

There is an additional way to do that that doesn’t rely on an external file (or database) like the one you have presentred. If has been presented in the EJB Design Patterns book, written by Floyd Marinescu, and available in a pdf format for free from the given link.

The suggested solution is based on the UUID for EJB pattern, that comes out from this question: How can universally unique primary keys can be generated in menory without requiring a database or a singleton? Without enetring in the specifics (you can fully check out the pattern by reading the appropriate chapter), the solution is to generate a 32 digit key, encoded in hexadecimal composed as follows:

  • Unique down to the millisecond. Digits 1-8 are are the hex encoded lower 32 bits of the System.currentTimeMillis() call.
  • Unique across a cluster. Digits 9-16 are the encoded representation of the 32 bit integer of the underlying IP address.
  • Unique down to the object in a JVM. Digits 17-24 are the hex representation of the call to System.identityHashCode(), which is guaranteed to return distinct integers for distinct objects within a JVM.
  • Unique within an object within a millisecond. Finally digits 25-32 represent a random 32 bit integer generated on every method call using the cryptographically strong java.security.SecureRandom class.

27) Is there some kind of Design pattern which would make it possible to use the Same code base in EJB and non EJB context?

A good suggestion would be using Delegation
[code lang=”java”]
class PieceOfCode {
public Object myMethod() {}
}
class EJBImpl … {
PieceOfCode poc = new PieceOfCode();
public Object myMethod() {
return poc.myMethod();
}
}
[/code]
This should not be a violation of EJB specs, since EJBs can use simple java classes for their use. Think about Dependant Objects and so on.

28) What is session facade?

Session facade is one design pattern that is often used while developing enterprise applications.

It is implemented as a higher level component (i.e.: Session EJB), and it contains all the iteractions between low level components (i.e.: Entity EJB). It then provides a single interface for the functionality of an application or part of it, and it decouples lower level components simplifying the design.

Think of a bank situation, where you have someone that would like to transfer money from one account to another.

In this type of scenario, the client has to check that the user is authorized, get the status of the two accounts, check that there are enough money on the first one, and then call the transfer. The entire transfer has to be done in a single transaction otherwise is something goes south, the situation has to be restored.

As you can see, multiple server-side objects need to be accessed and possibly modified. Multiple fine-grained invocations of Entity (or even Session) Beans add the overhead of network calls, even multiple transaction. In other words, the risk is to have a solution that has a high network overhead, high coupling, poor reusability and mantainability.

The best solution is then to wrap all the calls inside a Session Bean, so the clients will have a single point to access (that is the session bean) that will take care of handling all the rest.

Obviously you need to be very careful when writing Session Facades, to avoid the abusing of it (often called God-Bean).

For a detailed description of this pattern, check this page: Core J2EE Patterns Session Facade or get Floyd Marinescu’s EJB Design Patterns, in PDF format.

29) How is JDO different from VO ?

JDO is a persistence technology that competes against entity beans in enterprise application development. It allows you to create POJOs (plain old java objects) and persist them to the database letting JDO take care of the storage.

Value objects, on the other hand, represent an abstract design pattern used in conjuction with entity beans, jdbc, and possibly even JDO to overcome commonly found isolation and transactional problems in enterprise apps. Value objects alone do not allow you to persist objects they are simple data holders used to transfer data from the database to the client and back to the database.

Side note: I know that many books out there still refer to these data holders as value objects but the correct term is DTO: data transfer objects. Value objects refer to objects that hold a value. A good example of this java.lang.Integer object which holds an int.

30) How can I implement the MVC design pattern using JSP?

The MVC (Model View Controller) design pattern is a pattern/architecture that can be used by GUI’s. It seperates the application’s data, user interface and control logic into three separate entities. This ensures the system will be more maintainable in the future as changes to one component will not have an affect on the others.

The MVC pattern also conforms with the JSP Model 2 architecture.

The MVC pattern can be easily implemented in web applications using JSTL core, JSP, Servlets and JavaBeans.

JSTL makes it easy for HTML designers to use dynamic data in their pages without having to learn in depth java. The tags are in a recognizable HTML like format meaning a smaller learning curve than taking on the JSP specification after taking on the Java specification.

JSTL also makes it easy for web developers who are developing all aspects of the application in helping you keep the content separate from the display by keeping your JSP clean from any Java code. Since JSTL and its EL (expression Language) are really only suited for accessing data, it forces you to use a MVC pattern so long as you keep all JSP and Java syntax/code out of the JSP pages.

A common scenario might look like this, a user sends a request to a server. The request is handled by a Servlet (the controller) which will initialize any JavaBeans (the model) required to fulfill the user’s request. The Servlet (the controller) will then forward the request, which contains the JavaBeans (the model), to a JSP (the view) page which contains only HTML and JSTL syntax. The JSTL will format the data into a human readable format before being sent back to the user. Thus completing the full MVC process.

JSTL also has a tag library for XML processing, this could be used in an MVC environment as you could replace the JavaBeans with an XML document to describe your data, so long as the XML is still constructed in a controller such as a Servlet before being passed to the JSP (the view).

JSTL also has a tag library for database access, using this in your JSP (the view) pages would NOT comply to the MVC pattern as there will be no separation between the model and the view.

Filed Under: Interview Questions Tagged With: Design Patterns

Decorator Design Pattern in Java

August 7, 2008 by Krishna Srinivasan Leave a Comment

This tutorial explain the basic concept of decorator design pattern and how to use them. This is one of the pattern I have published as part of our Design pattern in Java series. If you are interested in receiving updates, please subscribe our newsletter.

Intent of Decorator Design Pattern:

  • Attach additional responsibilities to an object dynamically.Decorators provide a flexible alternative to subclassing for extending functionality.[GoF,p175]
  • Client specified embellishment of a core object by recursively wrapping it.
  • Wrapping a gift,putting it in a box and wrapping the box.

also read:

  • Design Pattern Interview Questions
  • Factory Design Pattern
  • State design pattern

Problem:You want to add behavior or state to individual objects at runtime.Inheritance is not feasible because it is static and applies to an entire class.

Solution:Attach additional logic to an existing object.Use Delegation.Place an object in front of it that delegates calls to the original object and then makes needed changes before returning the value.This is a form of linked list.

Structural Summary:

  • Identify if the client would like to dynamically embellish a core object.
  • Start with a composite design and change the 1-to-many recursive relationship to 1-1.
  • Define each “embellishment” class a derived class of the class whose role has morphed from “Composite” to “Decorator”.
  • The client can now wrap a “core” object with any number of Decorator objects.Each decorator contributes its “embellishment” functionality and then delegates to its wrappee.

Decorator Design Pattern

Decorator Pattern involves encapsulating the original object inside an abstract wrapper interface.Both the decorator objects and the core object inherit from this abstract interface.

The interface uses recursive composition to allow an unlimited number of decorator “layers” to be added to each core object.Note that this pattern allows responsibilities to be added to an object,not methods to an object’s interface.

This interface presented to the client must remain constant as successive layers are specified.Also note that the core object identity has now been “hidden” inside of a decorator object.Trying to access core object is now a problem.

Decorator Design Pattern

  • Factory Pattern
  • Template Pattern
  • Abstract Factory Pattern

The Decorator attaches additional responsibilities to an object dynamically. The ornaments that are added to pine or fir trees are examples of Decorators. Lights, garland, candy canes, glass ornaments, etc., can be added to a tree to give it a festive look. The ornaments do not change the tree itself which is recognizable as a Christmas tree regardless of particular ornaments used. As an example of additional functionality, the addition of lights allows one to “light up” a Christmas tree.

Decorator Design Pattern

One class takes in another class both of which extend the same abstract class,and adds functionality.Decorator Pattern helps to add behavior or responsibilities to an object.This is also called “wrapper”.

Java Design Patterns suggest that decorators should be abstract classes and the concrete implementation should be derived from them.Decorator and Adapter patterns are similar.Adapter also seems to decorate classes.

The intent of using adapter is to convert the interface of one or more classes to suit the interface of the client program.In case of decorator,the intent is to add behavior and functionality to some of the objects,not all the objects or adding different functionalities to each of the objects.Can also be called as “Wrapper”.

Decorator Design Pattern Example ( Image Credit )

This pattern can also be used as a way to refactor a complex class into smaller pieces.Even if we donot need to attach responsibilities dynamically it can be clearer to have each responsibility in a different class.

Only disadvantage is code maintenance can be a problem as it provides the system with a lot of similar looking small objects(each decorator).

Difference that we see between a decorator pattern and subclassing is that we can decorate any class that implements an interface with a single class.Say we wanted to give ourselves a java.util.Map that printed a message whenever as added or removed a key.

We may create a subclass of HashMap i.e PrintableMap and override put and remove methods.But if we wanted to create a printable version of TreeMap then we either create PrintableTreeMap which has almost identical code to PrintableMap?(which should itself become PrintingHashMap) or we create a Map decorator.

Important Points about Decorator Design Pattern:

  • Ensure the context is: a single core(or non-optional) component,several optional wrappers and an interface that is commonto all.
  • Create a “Lowest Common Denominator” interface that makes all classes interchangeable.
  • Create a second level base class(Decorator) to support the optional wrapper classes.
  • Core class and Decorator class inherit from LCD interface.
  • Decorator class declares a composition relationship to the LCD interface,and this data member is initialized in its constructor.
  • Decorator class delegates to the LCD object.
  • Define a Decorator Derived class for each object embellishment.
  • Decorator derived classes implement their wrapper functinality and delegate to the Decorator base class.
  • 9) Client configures the type and ordering of Core and Decorator objects.

Rules of Thumb:
Adapter provides a different interface to its subject.Proxy provides the same interface.Decorator provides an enhanced interface.[GoF, p216]

Adapter changes the object’s interface,Decorator enhances an object’s responsibilities.Decorator is thus more transparent to the client.As a consequence,Decorator supports recursive composition,which isnt possible with pure Adapters.[GoF, p149]

Composite and Decorator have similar structure diagrams,reflecting the fact that both rely on recursive composition to organize an open-ended number of objects.[GoF, p219]

A Decorator can be viewed as a degenerate Composite with only one component.However a decorator adds additional responsibilities-it isnt intended for object aggregation.[GoF, p184]

Decorator is designed to let you add responsibilites to objects without subclassing.Composite’s focus is not an embellishment but on representation.These intents are distinct but complementary.Consequently Composite and Decorator are often used in concert. [GoF, p220]

Decorator lets us change the skin of an object.Strategy lets us change the guts.[GoF, p184]

Decorator and Proxy have diff purposes but similar structures.Both describe how to provide a level of indirection to another object,and the implementations keep a reference to the object to which they forward requests.[GoF, p220]

Below example gives one implementation of Decorator Pattern used in our project.Please note that we are using Apache Beehieve for our front-end application.

In our project we have a requirement to encrpt all the input data shown in jsp pages.Actually the idea and implementation was done by one developer named Sai Selvam in our project.Thankfully all of us learned from him.

Below are the steps:-

1) Create a class Crypto which extends from org.apache.beehive.netui.tags.html.Parameter class and overside setName and setValue methods and set the encrpyted names and values instead.

[code lang=”java”]public class Crypto extends Parameter
@Override
public void setName(String arg0)
super.setName(CryptoUtil.encrypt(arg0));
@Override
public void setValue(Object arg0) throws JspException
super.setValue(CryptoUtil.encrypt(String.valueOf(arg0)));
}[/code]

Please note that CryptoUtil is our project related class and we using BASE64Decoder and BASE64Encoder classes for achieving encryption and decryption which we will not be discussing in this article.Please refer manual (sun.misc.BASE64Decoder and sun.misc.BASE64Encoder) for further details.

2) Create a URLRewriteFilter class which acts as a filter i.e implements Filter interface.Cast the request object to CryptoWrappedRequest wrapper class which is extending from HttpServletRequestWrapper class.

[code lang=”java”]
public void doFilter(ServletRequest pRequest , ServletResponse pResponse,
FilterChain pChain) throws IOException , ServletException {
if (pRequest instanceof HttpServletRequest) {
HttpServletRequest request = (HttpServletRequest) pRequest;
HttpServletResponse response = (HttpServletResponse) pResponse;
CryptoWrappedRequest cryptoWrappedRequest = new CryptoWrappedRequest(request , response);
cryptoWrappedRequest.getRequestDispatcher(request.getServletPath()).forward(cryptoWrappedRequest , response);
if (!response.isCommitted()) {
pChain.doFilter(request , response);}[/code]

3) Create CryptoWrappedRequest class which extends from HttpServletRequestWrapper class and provides additional functinalities.

[code lang=”java”]
import org.apache.beehive.netui.pageflow.PageFlowUtils;
import org.apache.beehive.netui.pageflow.internal.PageFlowRequestWrapper;
public class CryptoWrappedRequest extends HttpServletRequestWrapper {
private PageFlowRequestWrapper pageFlowRequestWrapper;
private String newQueryString = null;
private Map<String, String[]> params = null;
public CryptoWrappedRequest(HttpServletRequest request , HttpServletResponse response) {
super(request);
pageFlowRequestWrapper = PageFlowRequestWrapper.wrapRequest(request);
}

@Override
public String getQueryString() {
if (newQueryString == null)
constructQueryString(pageFlowRequestWrapper.getQueryString());
return newQueryString;
}

// If the request has some query parameters appended to the URL then we decrypt key,value pairs and then
// append and form the newQueryString text approximately.If there is no data appended newQueryString value remains the same old value
//retrieved from pageFlowRequestWrapper.

protected void constructQueryString(String encryptedQueryString) {
if (encryptedQueryString != null &amp;amp;&amp;amp; encryptedQueryString.length() > 0) {
for(String param : encryptedQueryString.split("&amp;amp;")) {
String[] paramNameValuePair = param.split("=");
try {
if(paramNameValuePair.length>1)
{
String paramName = URLDecoder.decode(paramNameValuePair[0] , "UTF-8");
String paramValue = URLDecoder.decode(paramNameValuePair[1] , "UTF-8");
addToQueryString(paramName , paramValue);
}
}
catch (UnsupportedEncodingException e) {
//e.printStackTrace();
}
catch (Exception ex) {
//e.printStackTrace();
}
}
} else {
newQueryString = encryptedQueryString;
}
}

// This Method tries to decrypt the key and value before forming the newQueryString value.
protected void addToQueryString(String paramKey, String paramValue) {
String pmKeyDecrypted = CryptoUtil.decrypt(paramKey);
String pmValueDecrypted = CryptoUtil.decrypt(paramValue);

if (pmKeyDecrypted == null) { pmKeyDecrypted = paramKey; }
if (pmValueDecrypted == null) { pmValueDecrypted = paramValue; }

if (newQueryString == null) { newQueryString = ""; }
StringBuffer newQS = new StringBuffer(newQueryString);
if (newQS.length() > 0) { newQS.append("&amp;amp;"); }
newQS.append(pmKeyDecrypted);
newQS.append("=");
newQS.append(pmValueDecrypted);
newQueryString = newQS.toString();
}

@Override
public String getParameter(String paramName) {
if (pageFlowRequestWrapper.getParameter(paramName) != null) {
return pageFlowRequestWrapper.getParameter(paramName);
}
else if (pageFlowRequestWrapper.getParameter(CryptoUtil.encrypt(paramName)) != null) {
return CryptoUtil.decrypt(pageFlowRequestWrapper.getParameter(CryptoUtil.encrypt(paramName)));
}
return null;
}

@Override
public Enumeration getParameterNames() {
List<String> resultList = new ArrayList<String>();
Enumeration enn = pageFlowRequestWrapper.getParameterNames();
while(enn.hasMoreElements()) {
String paramName = (String)enn.nextElement();
String newName = CryptoUtil.decrypt(paramName);
if (newName != null) {
resultList.add(newName);
} else {
resultList.add(paramName);
}
}
return Collections.enumeration(resultList);
}

@Override
public String[] getParameterValues(String paramName) {
String[] result = null;
List<String> resultList = new ArrayList<String>();

String[] paramValues = pageFlowRequestWrapper.getParameterValues(paramName);
if (paramValues == null || paramValues.length == 0)
paramValues = pageFlowRequestWrapper.getParameterValues(CryptoUtil.encrypt(paramName));

if (paramValues != null &amp;amp;&amp;amp; paramValues.length > 0) {
for(String paramValue : paramValues) {
String newValue = CryptoUtil.decrypt(paramValue);
if (newValue != null)
resultList.add(newValue);
else
resultList.add(paramValue);
}
}

if (resultList.size() > 0) {
result = new String[resultList.size()];
resultList.toArray(result);
}

return result;
}

@Override
public Map getParameterMap()
{
if (params == null)
processParameters(pageFlowRequestWrapper.getParameterMap());

return params;
}

protected void processParameters(Map pm) {
//Map pm = pageFlowRequestWrapper.getParameterMap();
if (pm != null) {
params = new HashMap<String , String[]>();
Iterator pmIter = pm.keySet().iterator();
while(pmIter.hasNext()) {
String pmKey = (String) pmIter.next();
if (!pmKey.startsWith(PageFlowUtils.ACTION_OVERRIDE_PREFIX)) {
String pmKeyDecrypted = CryptoUtil.decrypt(pmKey);
if (pmKeyDecrypted == null) pmKeyDecrypted = pmKey;
for(String pmValue : (String[]) pm.get(pmKey)) {
String pmValueDecrypted = CryptoUtil.decrypt(pmValue);
if (pmValueDecrypted == null) pmValueDecrypted = pmValue;
addToParams(pmKeyDecrypted , pmValueDecrypted);
}
}
}
} else {
params = null;
}
}

protected void addToParams(String paramKey , String paramValue) {
List<String> listObj = new ArrayList<String>();

if (params.containsKey(paramKey)) {
Iterator iter = Arrays.asList((String[]) params.get(paramKey)).iterator();
while(iter.hasNext()) {
listObj.add((String) iter.next());
}
}
listObj.add(paramValue);
String[] strArray = new String[listObj.size()];
listObj.toArray(strArray);
params.put(paramKey , strArray);
}

}[/code]

4) Add entries in web.xml for Filter class and the Cryto tag which we defined in Step 1.Also create a .tld file refering to our cryto class.

5) Finally in jsp for any input parameter we will be sending we will write code similar to this.

[code lang=”java”]<crypto:EncryptParamter name="somename" value="value"/>[/code]

Filed Under: Java Tagged With: Design Patterns

Iterator Pattern

August 6, 2008 by Krishna Srinivasan Leave a Comment

What is Iterator Pattern?

Provide a way to access the elements of the aggregate object sequentially without exposing its underlying representation.
Aggregate object is an object that contains other objects for the purpose of grouping those objects as a unit.It is also called a container or a collection.Examples are linkedList,Hashtable,ArrayList etc.

also read:

  • Design Pattern Interview Questions
  • Factory Design Pattern
  • State design pattern

Motivation

  • Aggregate object such as a list should allow a way to traverse its elements without exposing its internal structure.
  • It should allow different traversal methods.
  • It should allow multiple traversals to be in progress concurrently.
  • But we really donot want to add all these methods to the interface for the aggregate.

Use of Iterator Pattern

  • To Support traversals of aggregate objects without exposing their internal representation.
  • To support multiple,concurrent traversals of aggregate objects.
  • To provide a uniform interface for traversing different aggregate structures
    (that is, to support polymorphic iteration)

Related Patterns

  • Composite – Iterators are often used to recursively traverse composite structures.
  • Factory Method – Polymorphic iterators use factory methods to instantiate the appropriate iterator subclass.

Iterator Pattern is one which allows us to navigate through a collection of data using a common interface without knowing its underlying implementation.Iterator Pattern should be implemented as interface.This allows every user to implement it in the manner which most likely suits the requirement.

One Real time example of Iterator Pattern is the usage of Remote Controls in Home.Any Remote Control we use to start pressing up and down and back keys to iterate through the channels.

What sort of interface can Iterator be in case of Remote Controls?

One Example Implementation might be:

[code lang=”java”]
public interface Iterator {
public Channel nextChannel(int currentChannel);
public Channel previousChannel(int currentChannel);
}
[/code]

The Channel iterator is common for all the remote controls.It’s like a specification implemented by all the remote control manufacturing companies.

[code lang=”java”]
public ChannelSurfer implements Iterator {

public Channel nextChannel(int currentChannel) {
Channel channel=new Channel(currentChannel+1);
return channel;
}

public Channel previousChannel(int currentChannel) {
Channel channel=new Channel(currentChannel-1);
return channel;
}
}

public class RemoteControl {

private ChannelSurfer surfer;

public RemoteControl() {
surfer=new ChannelSurfer();
}

public Program getProgram(ChannelSurfer surfer) {
return new Program(surfer.nextChannel());
}
}

public Program {

// … Some specific implementation of Program class.
}
[/code]

We all know that every channel is associated with program and it’s basically the program and not the channel number which a user wants to see.This applies that we can apply some logic before returning the elements through iterator.Iterator here can also be programmed to return ‘the programs’ straight away rather than returning the channels.

Common Java Iterator is Iterator itself.Interface Signature has been copied from the javadoc.

An iterator over a collection. Iterator takes the place of Enumeration in the Java collections framework. Iterators differ from enumerations in two ways:
Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
Method names have been improved.

[code lang=”java”]
public interface Iterator<E> {
boolean hasNext();
E next();
void remove();
}
[/code]

java.util.Collection interface a root interface in Collections hierarchy contains a method iterator() which returns the Iterator interface.Hence any class implementing Collection interface should provide definition for iterator() method.But please note that there are no Guarantees concerning the order(unless this collection is an instance of some class that provides a guarantee) as List by definition guarantees ordered Collection.

When we try to view List interface which extends Collection interface it has a method iterator() which returns an Iterator over the elements in this list in proper sequence.

Now coming to ArrayList a subclass class implementing List interface – which also extends AbstractList class provides definition for iterator() method.Infact all the underlying logic sits in AbstractList class.

When we try to view code it tries to return a Itr innerClass object.

[code lang=”java”]
public Iterator<E> iterator() {
return new Itr();
}

public E remove(int index) {
throw new UnsupportedOperationException();
}
[/code]

Now finally when we try to go through code of Itr we can see that this class implements Iterator interface naturally and provides definition for all methods.

Let us try to view few important parts of the code:

[code lang=”java”]
private class Itr implements Iterator<E> {

/**
* Index of element to be returned by subsequent call to next.
*/
int cursor = 0;

/**
* Index of element returned by most recent call to next or
* previous. Reset to -1 if this element is deleted by a call
* to remove.
*/
int lastRet = -1;

/**
* The modCount value that the iterator believes that the backing
* List should have. If this expectation is violated, the iterator
* has detected concurrent modification.
*/
int expectedModCount = modCount;

// Note that size() returns the no of elements count in the list.
public boolean hasNext() {
return cursor!=size();
}

public E next() {
checkForComodification();
try {
E next=get(cursor);
// Please note that the implementation for get() method is defined in indivudual subclasses like ArrayList class rather than AbstractList itself.
lastRet=cursor++;
return next;
}catch(IndexOutOfBoundsException ie) {
checkForComodification();
throw new NoSuchElementModification();
}
}

public void remove() {
if(lastRet==-1)
throw new IllegalStateException();
checkForComodification();
try {
AbstractList.this.remove(lastRet); // Please note that remove method will be called depending on the object called.Also an exception is thrown in the remove() method implementation of AbstractList class.

if (lastRet < cursor)
cursor–;
lastRet = -1;
expectedModCount = modCount;
} catch(IndexOutOfBoundsException e) {
throw new ConcurrentModificationException();
}

}

final void checkForComodification() {
if(modCount!=expectedModCount)
throw new ConcurrentModificationException();
}

}
[/code]

When we try to peep code of ArrayList class to check the implementation of get() method we find:

[code lang=”java”]
public E get(int index) {
RangeCheck(index);
return elementData[index]; // elementData is an array of type E.
}

/**
* Check if the given index is in range. If not, throw an appropriate
* runtime exception. This method does *not* check if the index is
* negative: It is always used immediately prior to an array access,
* which throws an ArrayIndexOutOfBoundsException if index is negative.
*/
private void RangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(
"Index: "+index+", Size: "+size);
}

When we try to view remove() method logic in ArrayList.

public E remove(int index) {
RangeCheck(index);

modCount++;
E oldValue = elementData[index];

int numMoved = size – index – 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[–size] = null;

return oldValue;
}

[/code]

It clearly tries to remove the specified element by shifting other if remaining elements to left and nullifies last element to null just to make sure if the user is trying to remove last element and finally returns back the value of the element to be removed.

Filed Under: Java Tagged With: Design Patterns

Abstract Factory Design Pattern

August 6, 2008 by Krishna Srinivasan Leave a Comment

This tutorial explain the basic concept of abstract factory design pattern and how to use them. This is one of the pattern I have published as part of our Design pattern in Java series. If you are interested in receiving updates, please subscribe our newsletter.

What is Abstract Factory Design Pattern?

Abstract Factory Design Pattern

Provide an interface for creating families of related or dependent objects without specifying their concrete classes.

Wikipedia says:
A software design pattern, the Abstract Factory Pattern provides a way to encapsulate a group of individual factories that have a common theme.

also read:

  • Design Pattern Interview Questions
  • Factory Design Pattern
  • State design pattern

Intent:
Define an interface for creating an object,but let subclasses decide which class to instantiate.
Factory method lets a class instantiation to subclasses.

Motto: Hence depend on abstractions and not on concrete classes.Intent of Abstract Factory is to create families of related objects without having to depend on their concrete classes.A Simple Abstract Factory is a way to decouple our clients from concrete classes.Abstract Factory relies on Object Composition.Object creation is implemented in methods exposed in the factory interface.[GoF,162]

Purpose:
To create a contract for creating families of related or dependent objects without having to specify their concrete classes.

Introduction:
Suppose we plan to manage address and telephone information in our application(Example Personal Informational manager) system.We will initially produce classes to represent Address and Telephone number data.Code these classes so that they store the relavent information and enforce business rules about their format.Ex: In few indian cities all telephone numbers are limited to 7 digits.Shortly we get another requirement to manage this application for another city/country.So we modify our logic in the Address and PhoneNumber to satisfy rules for another city/country and all of a sudden after managing for many countries sees our classes get bloated with code and difficult to manage. With every country added, we need to modify and recompile the classes to manage contact information.

It’s better to flexibly add these paired classes to the system;to take the general rules that apply to address and phone number data,and allow any number of possible foreign variations to be “loaded” into a system.

The abstract factory solves this problem.Using this pattern,you define an AddressFactory- a generic framework for producing objects that follow the general pattern for an Address and PhoneNumber.At runtime,this factory is paired with any number of concrete factories for different countries,and each country has its own version of Address and PhoneNumber classes.

Instead of going through nightmare of adding functional logic to the classes,extend the Address to USAddress and PhoneNumber to USPhoneNumber for country US.Instances of both classes are created by USAddressFactory.This gives greater freedom to extend your code without having to make major structural modifications in the rest of the system.

Applicability:
Use the Abstract Factory Pattern when:

  • The client should be independent of how the products are created.
  • Application should be configured with one of multiple families of products.
  • Objects needs to be created as a set,in order to be compatible.
  • You want to provide a collection of classes and you want to reveal just their contracts and their relationships,not their implementations.

Description:
During runtime,ConcreteFactories and ConcreteProducts are created and used by the application.The concrete classes conform to the contract defined by the AbstractFactory and AbstractProducts so the concrete classes can be directly used,without being recoded or recompiled.

We typically use the following to implement the Abstract Factory Pattern:

  • AbstractFactory – An abstract class or interface that defines the create methods for abstract products.
  • AbstractProduct – An abstract class or interface that describing the general behavior of the resource that will be used by the application.
  • ConcreteFactory – A class derived from the abstract factory.It implements create methods for one or more concrete products.
  • ConcreteProduct – A class derived from the abstract product,providing an implementation for a specific resource or operating environment.

Benefits and Drawbacks

Abstract Factory helps to increase the overall flexibility of the application.Flexibility manifests itself both during runtime and design time.During design we donot have to predict all future uses of this application.Instead we create a generic framework,and develop implementations independently from the rest of the application.At runtime,application can easily integrate new features and resources.

A further benefit of this pattern is it simplifies testing the rest of the application.

As discussed,we can define the AbstractFactory and AbstractProduct as an interface or an abstract class depending on the needs of the application and your preference.

Depending on how the factory is to be used,some variations of this pattern allow multiple ConcreteFactory objects to be produced,resulting in an application that can simultaneously use multiple families of ConcreteProducts.

Related Patterns

  • Factory Method – Used to implement Abstract Factory.
  • Singleton – Often Used in Concrete Factory.
  • Data Access Object – The Data Access Object pattern can use the Abstract Factory Pattern to add flexibility in creating Database-specific factories.

Implementation Issues

How many instances of a particular concrete factory should there be?

  • An application typically only needs a single instance of a particular concrete factory
  • Use the Singleton pattern for this purpose

Below example describes implementation of Abstract Factory.

[code lang=”java”]

package patterns;

interface AddressFactory {

public Address createAddress();
public PhoneNumber createPhoneNumber();
}

abstract class Address {
private String street;
private String city;
private String region;
private String postalCode;

public static final String EOL_STRING =System.getProperty("line.separator");
public static final String SPACE = " ";

public String getStreet() {
return street;
}
public String getCity() {
return city;
}
public String getPostalCode() {
return postalCode;
}
public String getRegion() {
return region;
}
public abstract String getCountry();

public String getFullAddress() {
return street + EOL_STRING + city + SPACE + postalCode + EOL_STRING;
}
}

abstract class PhoneNumber {
private String phoneNumber;
abstract String getCountryCode();

public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
}

class USAddressFactory implements AddressFactory{
public Address createAddress(){
return new USAddress();
}

public PhoneNumber createPhoneNumber(){
return new USPhoneNumber();
}
}

class USAddress extends Address{
private static final String COUNTRY = "UNITED STATES";
private static final String COMMA = ",";

public String getCountry(){ return COUNTRY; }

public String getFullAddress(){
return getStreet() + EOL_STRING +
getCity() + COMMA + SPACE + getRegion() +
SPACE + getPostalCode() + EOL_STRING +
COUNTRY + EOL_STRING;
}
}

class USPhoneNumber extends PhoneNumber{
private static final String COUNTRY_CODE = "01";
private static final int NUMBER_LENGTH = 10;

public String getCountryCode(){ return COUNTRY_CODE; }

public void setPhoneNumber(String newNumber){
if (newNumber.length() == NUMBER_LENGTH){
super.setPhoneNumber(newNumber);
}
}
}

class FrenchAddressFactory implements AddressFactory{
public Address createAddress(){
return new FrenchAddress();
}

public PhoneNumber createPhoneNumber(){
return new FrenchPhoneNumber();
}
}

class FrenchAddress extends Address{
private static final String COUNTRY = "FRANCE";

public String getCountry(){ return COUNTRY; }

public String getFullAddress(){
return getStreet() + EOL_STRING + getPostalCode() + SPACE + getCity() + EOL_STRING + COUNTRY + EOL_STRING;
}
}

class FrenchPhoneNumber extends PhoneNumber{
private static final String COUNTRY_CODE = "33";
private static final int NUMBER_LENGTH = 9;

public String getCountryCode(){ return COUNTRY_CODE; }

public void setPhoneNumber(String newNumber){
if (newNumber.length() == NUMBER_LENGTH){
super.setPhoneNumber(newNumber);
}
}
}

public class AbstractFactoryPattern {

public static void main(String[] args) {
Address fd=new FrenchAddressFactory().createAddress();
System.out.println("French Address:" + fd.getFullAddress());
}
}
[/code]

Filed Under: Java Tagged With: Design Patterns

Template Method Design Pattern

August 6, 2008 by Krishna Srinivasan Leave a Comment

This tutorial explain the basic concept of template method design pattern and how to use them. This is one of the pattern I have published as part of our Design pattern in Java series. If you are interested in receiving updates, please subscribe our newsletter.

What is Template Method Design Pattern?

Template Method Design Pattern

An abstract class defines various methods and has one non-overridden method which calls the various methods.

also read:

  • Design Pattern Interview Questions
  • Factory Design Pattern
  • State design pattern

Wikipedia Says:

A template method defines the program skeleton of an aligorithm.The aligorithm itself is made abstract,and the subclasses override the abstract methods to provide concrete behavior.First a class is created that provides the basic steps of an aligorithm design.These steps are implemented using abstract methods.Later on subclasses change the abstract methods to implement real actions.Thus the general aligorithm is saved in one place but the concrete steps may be changed by the subclasses.
Non-Abstract Methods are completly controlled by the Template Method.In contrast the template method need not be changed and is not an abstract operation and thus may guarentee required steps before and after the abstract operations.Thus the template method is invoked and as a consequence the non-abstract methods and abstract methods are called in the correct sequence.

Why Template Method?

Define the skeleton of an aligorithm in an operation,deferring some steps to subclasses.Template methods lets subclasses redefine certain steps of an aligorithm without changing the aligorithm structure .[DesignPatterns, p. 325]

Sometimes we want to specify the order of operations that a method uses,but allow sub-classes to provide their own implementation of some of these operations.When ever we see two methods in subclasses,it makes sense to bring the methods together into a superclass method.

When Template Method?

Use the Template method pattern:

  • To implement the invariant parts of an algorithm once and leave it up to sub-classes to implement the behavior that can vary.
  • To localize common behavior among subclasses and place it in a common class(in this case a superclass) to avoid code duplication.This is a classic example of “code refactoring”.
  • To control how subclasses extend superclass operations.You can define a template method that calls “hook” operations at specific points,there by permitting extensions only at that point.

THE TEMPLATE METHOD IS A FUNDAMENTAL TECHNIQUE FOR CODE REUSE

Problem:
Two different component have significant similarities,but demonstrate no reuse of common interface or implementation.If a change common to both components becomes necessary,duplicate effort must be expended.

Discussion:
The component designer decides which steps of an aligorithm are invariant(or standard) and which are variant(or customizable).The invariant steps are implemented in an abstract base class,while the variant steps are either given a default implementation or no implementation at all.The “variant” steps represent “hooks”,or “placeholders” that can or must be supplied by the component’s client in a concrete derived class.
The component designer mandates the required steps of an aligorithm,and the ordering of the steps,but allow the component client to extend or replace some number of steps.
Template methods are prominently used in frameworks.Each framework implements the invariant pieces of domain’s architecture,and defines “placeholders” for all necessary or interesting client customization options.The inverted control structure has been affectionately labelled “the hollywood principle” – Don’t call us we will call you.

Usage:
The template method is used to:

  • Let subclasses implement behavior that can vary.
  • Avoid duplication in the code.We look for general code in the aligorithm and implement variants in the subclasses.
  • Control at what point(s) subclassing is allowed.

Implementation Issues:

  • Operations which must be overridden by subclasses should be made abstract.
  • If the template method itself should not be overidden by subclasses it should be made final.
  • To allow a subclass to insert code at a specific spot in the operation of the aligorithm,insert “hook” operations into the template method.These hook operations may do nothing by default.
  • Try to minimize the number of operations that a subclass must override.
  • In a template method parent class calls the operations of a subclass and not the other way round.

Example:
The template method defines a skeleton of an aligorithm in an operation and defers some steps to subclasses.Home Builders use the template method when developing a new subdivision.A typical subdivision consits of a limited number of floor plans with diff variations available for each.Within a floor plan, the foundation, framing, plumbing, and wiring will be identical for each house. Variation is introduced in the later stages of construction to produce a wider variety of models. [Michael Duell, “Non-software examples of software design patterns”, Object Magazine, Jul 97, p54]

Template method pattern could be refactored using an interface that explicitly signals the methods requested to subclasses and also the state needed by them from the abstract class.

Rules of Thumb:
Strategy is like Template Method except in its granularity.[Coplien, C++ Report, Mar 96, p88]
Template method uses inheritance to vary part of an aligorithm.Strategy uses delegation to vary the entire aligorithm. [GOF, p330]

Also Alex has a good explanation of why he hates Template Pattern.Even i do agree to some extent.

Below example gives an implementation of Template Design Pattern.

[code lang=”java”]
package patterns;

abstract class TitleInfo {
private String titleName;

// The Template Method.
// Calls the concrete class methods,is not overridden

public final String processTitleInfo() {
StringBuffer titleInfo=new StringBuffer();
titleInfo.append(this.getTitleBlurb());
titleInfo.append(this.getDvdEncodingRegionInfo());
return titleInfo.toString();
}

public final void setTitleName(String titleNameIn) {
this.titleName=titleNameIn;
}

public final String getTitleName() {
return this.titleName;
}

public abstract String getTitleBlurb();

public String getDvdEncodingRegionInfo() {
return " ";
}

}

class DvdTitleInfo extends TitleInfo {
String star;
char encodingRegion;

public DvdTitleInfo(String titleName,String star,char encodingRegion) {
this.setTitleName(titleName);
this.setStar(star);
this.setEncodingRegion(encodingRegion);
}

public char getEncodingRegion() {
return encodingRegion;
}

public void setEncodingRegion(char encodingRegion) {
this.encodingRegion = encodingRegion;
}

public String getStar() {
return star;
}

public void setStar(String star) {
this.star = star;
}

public String getTitleBlurb() {
return ("DVD: " + this.getTitleName() + ", starring " + this.getStar());
}

public String getDvdEncodingRegionInfo() {
return (", encoding region: " + this.getEncodingRegion());
}
}

class BookTitleInfo extends TitleInfo {
private String author;

public BookTitleInfo(String titleName,String author) {
this.setAuthor(author);
this.setTitleName(titleName);
}

public String getAuthor() {
return author;
}

public void setAuthor(String author) {
this.author = author;
}

public String getTitleBlurb() {
return ("Book: " + this.getTitleName() + ", Author: " + this.getAuthor());
}
}

public class TemplatePatternDemo {

public static void main(String[] args) {
TitleInfo bladeRunner=new DvdTitleInfo("Blade Runner","Harrison Ford",’1′);
TitleInfo electricSheep=new BookTitleInfo("Do Androids Dream of Electric Sheep?","Philip");

System.out.println(" ");
System.out.println("Testing bladeRunner" + bladeRunner.processTitleInfo());
System.out.println("Testing electricSheep" + electricSheep.processTitleInfo());
}
}
[/code]

Filed Under: Java Tagged With: Design Patterns

  • 1
  • 2
  • Next Page »

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved