• Skip to primary navigation
  • Skip to content
  • Skip to primary sidebar
  • Skip to footer
  • Core Java
  • Design Patterns
  • JSP
  • Servlets
  • Building Tools
  • jQuery
  • Spring
  • Hibernate
  • Mongo DB
  • More
    • HTML
    • SCJP
    • AJAX
    • UML
    • Struts
    • J2EE
    • Testing
    • Angular JS

J2EE Reference

  • Home
  • About Us
    • Java Learning Centers
  • Contact Us

Design Patterns

Iterator Design Pattern Implementation using Java

July 21, 2017 By j2eereference Leave a Comment

What is Iterator Design Pattern?

Iterator design pattern is used for finding a method to operate the elements in a collection in an orderly approach without any need for knowing its primary representation. Iterator pattern is a type of behavioural pattern and it is the most frequently used design pattern in Java programming.

Iterator Design Pattern Implementation Using Java

Consider an example containing list of movies.  Client program requires traversing through the list of movies on the whole or based on the language of the movie. Few client programs might require only English movies and they want to access only English movies by avoiding other languages. In this case, Iterator design pattern can be utilized and iteration can be offered on the basis of language of the movie.

Given below is the complete source code to implement this scenario using Iterator design pattern:

Movie.java

Movie.java is a plain POJO class which includes elements, movieName and language.

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class Movie {
private String movieName;
private String movieLanguage;
public Movie(String movieName, String movieLanguage) {
this.movieName = movieName;
this.movieLanguage = movieLanguage;
}
public String getMovieName() {
return movieName;
}
public void setMovieName(String movieName) {
this.movieName = movieName;
}
public String getMovieLanguage() {
return movieLanguage;
}
public void setMovieLanguage(String movieLanguage) {
this.movieLanguage = movieLanguage;
}
}

iPlayer.java

iPlayer is the base interface.

Java
1
2
3
4
5
6
7
8
import java.util.List;
 
public interface iPlayer {
public List<Movie> getMovies();
public void addMovie(Movie movie);
public void removeMovie(Movie movie);
public iIterator createIterator(String iteratorType);
}

PlayerImpl.java
Next step is to implement the Iterator.

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import java.util.ArrayList;
import java.util.List;
 
public class PlayerImpl implements iPlayer {
List<Movie> movieList;
 
public PlayerImpl() {
movieList = new ArrayList<Movie>();
}
 
@Override
public List<Movie> getMovies() {
 
return movieList;
}
 
@Override
public void addMovie(Movie movie) {
movieList.add(movie);
}
 
@Override
public void removeMovie(Movie movie) {
movieList.remove(movie);
}
 
@Override
public iIterator createIterator(String iteratorType) {
if ("English".equals(iteratorType)) {
return new EnglishIterator(movieList);
} else {
return new GermanIterator(movieList);
}
}
}

Here the iIterator interface is implemented by inner class style of implementation. So this implementation can never be utilized by any other aggregate.

iIterator.java

Java
1
2
3
4
5
public interface iIterator {
public Movie nextMovie ();
public boolean isLastMovie();
public Movie currentMovie();
}

EnglishIterator.java

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import java.util.List;
 
public class EnglishIterator implements iIterator{
private List<Movie> movieList;
private int position;
 
public EnglishIterator(List<Movie> movieList) {
this.movieList = movieList;
}
@Override
public Movie nextMovie() {
Movie movie = null;
for (; position < movieList.size(); position++) {
if ("English".equals(movieList.get(position).getMovieLanguage())) {
movie = movieList.get(position);
position++;
break;
}
}
return movie;
}
 
@Override
public boolean isLastMovie() {
for (int i = position; i < movieList.size(); i++) {
if ("English".equals((movieList.get(i)).getMovieLanguage())) {
return false;
}
}
return true;
}
 
@Override
public Movie currentMovie() {
if (position < movieList.size()) {
return movieList.get(position);
}
return null;
}
}

GermanIterator.java

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import java.util.List;
 
public class GermanIterator implements iIterator {
List<Movie> movieList;
private int position;
 
public GermanIterator(List<Movie> movieList) {
this.movieList = movieList;
}
 
@Override
public Movie nextMovie() {
Movie movie = null;
for (; position < movieList.size(); position++) {
if ("German".equals((movieList.get(position)).getMovieLanguage())) {
movie = movieList.get(position);
position++;
break;
}
}
return movie;
}
 
@Override
public boolean isLastMovie() {
for (int i = position; i < movieList.size(); i++) {
if ("German".equals((movieList.get(i)).getMovieLanguage())) {
return false;
}
}
return true;
}
 
@Override
public Movie currentMovie() {
if (position < movieList.size()) {
return movieList.get(position);
}
return null;
}
}

IteratorCheck.java

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class IteratorCheck {
public static void main(String args[]) {
PlayerImpl player = new PlayerImpl();
player.addMovie(new Movie("Father", "English"));
player.addMovie(new Movie("Mummy", "English"));
player.addMovie(new Movie("Vater", "German"));
player.addMovie(new Movie("Godfather", "English"));
player.addMovie(new Movie("Wilder Stier", "German"));
 
iIterator englishIterator = player.createIterator("English");
while (!englishIterator.isLastMovie()) {
System.out.println("English Movie: "
+ englishIterator.nextMovie().getMovieName());
}
 
iIterator germanIterator = player.createIterator("German");
while (!germanIterator.isLastMovie()) {
System.out.println("German Movie: "
+ germanIterator.nextMovie().getMovieName());
}
}
}

Output will be:

English Movie: Father
English Movie: Mummy
English Movie: Godfather
German Movie: Vater
German Movie: Wilder Stier

Related Posts

  • Observer pattern
  • Façade pattern
  • What is Design pattern ?
  • Design pattern – Service Locator
  • Singleton

Filed Under: Design Patterns

Strategy Design Pattern Implementation using Java

July 20, 2017 By j2eereference Leave a Comment

What is Strategy Design Pattern?

Strategy design pattern, also called as policy design pattern is utilized for managing (i) algorithms, (ii) relationships and (iii) responsibilities among the objects. Strategy design pattern is a behaviour pattern. In this pattern, a class algorithm or its behaviour can be altered during run time.

Few Strategy design pattern examples include

  • Documents being saved in various file formats like .docx, .html, .rtf and excel documents saved as .xls, .csv.
  • Files being compressed by .zip, .rar and image files being compressed as .jpeg, .png, .bmp, .tif
  • Using various formats like bar chart, points etc, for plotting the same statistics.

 Purpose of Strategy Design Pattern

Strategy design pattern is intended to define a group of algorithms, then encapsulate each of the algorithms and permit them to become interchangeable. Strategy aims at letting the algorithm differ independently from Clients who are using it.

 Strategy Design Pattern Implementation using Java

Strategy design pattern is now demonstrated with an example. It is illustrated step by step.

Step 1: First a Strategy interface is created which describes an operation.

OperationStrategy.java

 

Java
1
2
3
public interface OperationStrategy {
   public int arithmeticOperation(int m, int n);
}

Step 2: In the next step, concrete classes are created. Here three implementations are made, one each for addition, subtraction and multiplication.

Addition.java

Java
1
2
3
4
5
6
public class Addition implements OperationStrategy{
   @Override
   public int arithmeticOperation(int m, int n) {
      return m + n;
   }
}

Subtraction.java

Java
1
2
3
4
5
6
public class Subtraction implements OperationStrategy{
@Override
   public int arithmeticOperation(int m, int n) {
      return m - n;
   }
}

Multiplication.java

Java
1
2
3
4
5
6
public class Multiplication implements OperationStrategy{
   @Override
   public int arithmeticOperation(int m, int n) {
      return m * n;
   }
}

Step 3: The Context Class is created in the next step. The context is used for observing the alteration in its behavior when the strategy is altered.

OperationContext.java

Java
1
2
3
4
5
6
7
8
9
10
public class OperationContext {
   private OperationStrategy strategy;
 
   public OperationContext(OperationStrategy strategy){
      this.strategy = strategy;
   }
   public int performStrategy(int m, int n){
      return strategy.arithmeticOperation(m, n);
   }
}

Step 4: As shown below, StrategyPatternTrial, the demo class, will utilize OperationContext and strategy objects for representing alteration in Context behaviour on the basis of the strategy it uses.

StrategyPatternTrial.java

Java
1
2
3
4
5
6
7
8
9
10
11
public class StrategyPatternTrial {
public static void main(String[] args) {
      OperationContext context = new OperationContext(new Addition());
      System.out.println("12 + 4 = " + context.performStrategy(12,4));
      context = new OperationContext(new Subtraction());
      System.out.println("12 - 4 = " + context.performStrategy(12, 4));
 
      context = new OperationContext(new Multiplication());
      System.out.println("12 * 4 = " + context.performStrategy(12, 4));
   }
}

Step 5: After execution, output of the above program would be:

12 + 4 = 16
12 – 4 = 8
12 * 4 = 48

Filed Under: Design Patterns

Decorator Design Pattern

July 19, 2017 By j2eereference Leave a Comment

What is Decorator Design Pattern?

Decorator Design Pattern is intended to add new functionality to an already existing object without modifying its structure. Decorator Design Pattern involves creation of decorator class that will wrap original class within itself and add additional functionality in the decorator class thereby keeping the signature of original class methods intact. That’s the reason why Decorator class is also termed as “Wrapper”.  For example, if we have created 10 objects among which we need to provide additional behavior for just 2 objects among those ten, then we can achieve it using Decorator Pattern.

Design patterns suggest that the Decorator class has to be an abstract class which is then inherited by concrete classes and these concrete classes have to implement the additional behavior.

Purpose of Decorator Design Pattern

Intended purpose of Decorator Design Pattern is to dynamically append additional responsibilities to an existing object.

Decorator Design Pattern Implementation using Java

To demonstrate Decorator Design Pattern, we will consider the shape example. There is an iShape interface that is implemented by two concrete classes namely Square and Rectangle. The iShape interface has a drawShape method which can be overridden by concrete classes to display what shape is being drawn.

Now we have to decorate the shape by giving yellow color for the borders. In order to add this new functionality to the shapes, we do not modify the iShape interface or its associated concrete classes. Instead we create a decorator class which incorporates this additional functionality and the decorator class wraps the shape interface objects within itself.

This scenario is implemented through the code shown below:

Creation of iShape interface with drawShape method:

 

Java
1
2
3
public interface iShape {
public void drawShape();
}

 

Creation of concrete classes Rectangle and Square that implements the iShape interface and overrides the drawShape method of iShape interface:

 

Java
1
2
3
4
5
6
7
public class Rectangle implements iShape {
 
@Override
public void drawShape(){
System.out.println("Currently drawing Rectangle Shape");
}
}

 

Java
1
2
3
4
5
6
7
public class Square implements iShape {
 
@Override
public void drawShape(){
System.out.println("Currently drawing Square Shape");
}
}

 

Now comes the creation of abstract decorator class that implements the iShape interface:

 

Java
1
2
3
4
5
6
7
8
9
10
11
public abstract class DecoratorForShape implements iShape {
protected iShape shapeToBeDecorated;
public DecoratorForShape(iShape shapeToBeDecorated){
this.shapeToBeDecorated = shapeToBeDecorated;
}
public void drawShape(){
shapeToBeDecorated.drawShape();
}
}

The next step is the creation of concrete class that inherits from DecoratorForShape class. This concrete class is called YellowShapeDecorator and its intention is to color the shape object’s border in yellow color.

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class YellowShapeDecorator extends DecoratorForShape{
 
public YellowShapeDecorator(iShape shapeToBeDecorated){
super(shapeToBeDecorated);
}
@Override
public void drawShape(){
shapeToBeDecorated.drawShape();
setYellowBorder(shapeToBeDecorated);
}
private void setYellowBorder(iShape shapeToBeDecorated){
System.out.println("Border color of the Shape is Yellow");
}
}

Now let us test if the decorator class is working fine by writing a test class as shown below:

Java
1
2
3
4
5
6
7
8
9
10
public class TestDecoratorPattern {
public static void main(String[] args) {
iShape squareObj = new Square();
squareObj.drawShape();
iShape yellowBorderSquare = new YellowShapeDecorator(new Square());
yellowBorderSquare.drawShape();
iShape yellowBorderRectangle = new YellowShapeDecorator(new Rectangle());
yellowBorderRectangle.drawShape();
}
}

Output will be:

Currently drawing Square Shape
Currently drawing Square Shape
Border color of the Shape is Yellow
Currently drawing Rectangle Shape
Border color of the Shape is Yellow

 

 

 

 

 

 

Filed Under: Design Patterns

Adapter Design Pattern Implementation using Java

July 18, 2017 By j2eereference Leave a Comment

What is Adapter Design Pattern?

Adapter Design Pattern behaves like a bridge between two interfaces that are incompatible. This Adapter Design Pattern incorporates one adapter class that is responsible for joining functionalities of interfaces that are incompatible or independent.

Real Time Example for Adapter Design Pattern

Best real time example for Adapter Design Pattern will be the card reader. The card reader is playing the role of an adapter between laptop and memory card. The memory card is plugged into the card reader and then the card reader is plugged into the laptop so that the memory card is read through laptop.

Purpose of Adapter Design Pattern

  • Based on Clients expectation, convert one class interface into another interface
  • Permit classes to work together irrespective of their incompatible interfaces

Adapter Design Pattern Implementation using Java

To demonstrate the Adapter Design Pattern, let us consider two shapes namely Square and Rectangle as example. Square and Rectangle are two different shapes, but when the length and width of a rectangle are equal, then it forms a square. Using this geometric condition, we are going to create an adapter for Rectangle to accommodate a square.

We will create an interface called “iSquare” which contains a method “calcArea” to calculate area of the square. This method will take only one parameter representing the side of the square.

Java
1
2
3
public interface iSquare {
public abstract void calcArea(int squareSide);
}

Then we will create a class that implements the interface and that class method will use appropriate formula to calculate area. This is demonstrated in the code snippet below:

Java
1
2
3
4
5
6
7
public class Square implements iSquare {
@Override
public void calcArea(int squareSide) {
int area = Math.pow(squareSide, 2);
System.out.println("Area is "+area);
}
}

Now, we will create another interface called “iRectangle” which contains a method “calcArea” to calculate area of the Rectangle. This method will take two parameters representing the length and width of the Rectangle.

Java
1
2
3
public interface iRectangle {
public abstract void calcArea(int rectLength, int rectWidth);
}

Then we will create a class that implements this interface and its associated abstract method.

Java
1
2
3
4
5
6
7
8
public class Rectangle implements iRectangle {
 
@Override
public void calcArea(int rectLength, int rectWidth) {
int area = rectLength * rectWidth;
System.out.println("Area is " +area);
}
}

Till now, it was a simple straight-forward example. Now our intention is to calculate area of the Square using an incompatible interface iRectangle. In order to achieve this, lets create an adapter class called RectSquareAdapter.

Java
1
2
3
4
5
6
7
8
9
10
11
public class RectSquareAdapter implements iSquare {
private iRectangle rect = null;
 
public  RectSquareAdapter(iRectangle rect){
this.rect = rect;
}
@Override
public void calcArea(int rectLength){
rect.calcArea(rectLength, rectLength);
}
}

This adapter class implements iSquare interface and within its calcArea method, it attempted to call calcArea method of iRectangle interface. Lets now test this adapter class:

 

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class TestAdapter{
 
public static void main(String[] args){
iSquare squareObject = new Square();
System.out.println("Calculating area of square with side as 10 using Square class...");
squareObject.calcArea(10);
 
iRectangle rectObject = new Rectangle();
System.out.println("Calculating area of rectangle with length as 5 and width as 4 using Rectangle class...");
rectObject.calcArea(5, 4);
 
rectObject = new Rectangle();
System.out.println("Calculating area of square with side as 5 using rectangle with the help of Adapter class... ");
RectSquareAdapter adapterObject = new RectSquareAdapter(rectObject);
adapterObject.calcArea(5);
}
}

 

Output will be:

Calculating area of square with side as 10 using Square class…

Area is 100.0

Calculating area of rectangle with length as 5 and width as 4 using Rectangle class…

Area is 20

Calculating area of square with side as 5 using rectangle with the help of Adapter class…

Area is 25

Thus these programs successfully demonstrate the adapter pattern by calculating area of square using the method of rectangle.  

Filed Under: Design Patterns

GOF Design Patterns

July 7, 2017 By j2eereference Leave a Comment

According to the Design Pattern book titled “Design Patterns: Elements of Reusable Object-Oriented Software”, there are altogether twenty-three design patterns. This book was written and published by four authors namely John Vlissides, Erich Gamma, Ralph Johnson, and Richard Helm. These four authors who hold the fundamental responsibility of introducing Design Patterns in the field of software programming are termed as “Gang of Four” authors, in short as GOF.

As per these authors, the GOF Design Patterns are classified into three different categories namely:

  • Creational Design Patterns
  • Structural Design Patterns
  • Behavioral Design Patterns

Through this article, we will learn about the above mentioned categories in detail.

Creational Design Patterns:

Creational Design Pattern provides a methodology for creating objects by hiding the logic of object creation. Creational Design Pattern talks about “when should the objects be created?” and “How should the objects be created?”.

Types of Creational Design Patterns:

Among the 23 GOF Design Patterns, 5 design patterns fall under the category of “Creational Design Patterns”. They are:

  1. Factory Pattern: To create an object of numerous derived classes.
  2. Abstract Factory Pattern: To create an object of numerous families of classes.
  3. Builder Pattern: To separate object construction and object representation.
  4. Prototype Pattern: To copy or clone a fully initialized object.
  5. Singleton Pattern: To create only one object / instance for a particular class.

Structural Design Patterns:

Structural Design Pattern is concerned about composition of class and composition of object.

 Types of Structural Design Patterns:

Among the 23 GOF Design Patterns, 7 design patterns fall under the category of “Structural Design Patterns”. They are:

  1. Adapter Pattern –To match the interfaces of diverse classes.
  2. Bridge Pattern – To separate interface of an object from the implementation of that object.
  3. Composite Pattern – To create a tree structure encompassing simple objects and composite objects.
  4. Decorator Pattern – To dynamically add objects with their responsibilities.
  5. Façade Pattern – To use a single class to represent a whole subsystem.
  6. Flyweight Pattern –To efficiently share instance that is fine-grained.
  7. Proxy Pattern – To demonstrate an object that represents another object.

Behavioral Design Patterns:

Behavioral Design Patterns are concerned about object communication.

Types of Behavioral Design Patterns:

Among the 23 GOF Design Patterns, 11 design patterns fall under the category of “Structural Design Patterns”. They are:

  1. Chain of Responsibility Pattern – To pass a request through a chain of objects.
  2. Command Pattern – To encapsulate command request by way of an object.
  3. Interpreter Pattern – To incorporate language elements within a program.
  4. Iterator Pattern – To sequentially access collection elements.
  5. Mediator Pattern – To define simplified communication among classes.
  6. Memento Pattern – To capture and to restore the internal state of an object.
  7. Observer Pattern – To notify change to several classes.
  8. State Pattern – To alter the behavior of an object when there is an associated state change.
  9. Strategy Pattern – To encapsulate an algorithm within a class.
  10. Template Method Pattern – To defer the actual algorithmic steps to a subclass.
  11. Visitor Pattern – To define a new operation for a class without changing it.

 

 

Filed Under: Design Patterns

History and Need for Design Patterns

July 6, 2017 By j2eereference Leave a Comment

What are Design Patterns?

The design patterns are nothing but proven solutions to common problems that the software developers face while developing the software. These proven solutions were attained through trial and error methods by several software developers after spending considerable time.

Design Patterns signify the best practices used by skilled software developers in object oriented methodology. It has to be noted that the design pattern is not a completed design, which can be converted directly into source code. Design pattern is a template indicating about how a problem can be solved.

History of Design Patterns

Design Patterns was instigated as an architectural model by Christopher Alexander in the period 1977 to 1979. According to this architectural model, the architectural design ideas were captured as reusable and archetypal descriptions.

In the year 1987, Ward Cunningham and Kent Beck started experimenting about how to apply patterns to software programming and they submitted their results at the OOPSLA conference that year. In the next few years, Kent Beck, Ward Cunningham and others followed up on this work.

Design patterns gained popularity after release of the book named “Design Patterns: Elements of Reusable Object-Oriented Software”. This book was issued in the year 1994 by the famous “Gang of Four” authors namely John Vlissides, Erich Gamma, Ralph Johnson, and Richard Helm. The “Gang of Four” authors are often condensed as “GOF”. This book initiated the concept of Design Patterns in Software Development.

Need for Design Patterns

  • Rather than having to re-invent the wheel, we can re-use an existing solution recognized across organizations as something that simply works. Since it is well documented, it is comparatively easier to visualize the problem and solution in our mind.
  • In many software projects, creation and implementation of entire project takes just 1/4th of total time and the maintenance of the project becomes a lengthy process thereby consuming more than 3/4th of total time. The reason behind this lengthy maintenance phase is that the project design is not efficient enough. Design Patterns eliminate this issue by decreasing the additional effort and maintenance cost by offering solutions that are very much reliable, efficient, and reusable.
  • Thus the key factors behind the success of design patterns are
    • (1) reusability,
    • (2) reliability
    • (3) efficiency due to high performance solution, and
    • (4) less time consumption as the solution is well tested and ready handed.

Filed Under: Design Patterns

Command Design Pattern

June 22, 2017 By j2eereference 1 Comment

Command Design Pattern : Command design pattern comes under behavioral design pattern. Command design patter is used to implement request-response model.

To understand command pattern in a better way, let’s understand key components first:

Command: A command is an interface which declares execute() method to execute a specific action.

Concrete Command : This class is an implementation of Command interface which provides actual implementation of execute() method.

Invoker : An invoker class contains a reference of  a command and  instructs the command to perform an action.

Receiver : A Receiver is a class which provides logic to perform actions asked by command.Execute() method of concrete command class invokes action method of receiver class.

Client : Client class will create instances of Receiver, Invoker and concrete command and then associates  ConcreteCommand with Receiver class to perform action.

In command design pattern, client class creates instance of concrete command and set receiver object in concrete command. After that it creates instance of Invoker class and set command object in it and then invoker class forwards request from client to command object .Invoker has no knowledge about action performed by receiver class it just invokes command which then executes the action of receiver class.

Client Class: CommandDemo.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.j2eereference.designPattern;
 
public class CommandDemo {
 
public static void main(String args[])
{
  //Receiver Class
  AdditionReceiver additionReceiver  = new AdditionReceiver();
  //Concrete command class
  Command addCommand = new AdditionCommand(additionReceiver);
  //Invoker class
  ActionInvoker actionInvoker = new ActionInvoker(addCommand);
  actionInvoker.invokeMethod();
}
}

Invoker class: ActionInvoker.java

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.j2eereference.designPattern;
 
public class ActionInvoker
{
  Command command;
  public ActionInvoker(Command command)
  {
    this.command = command;
  }
  public void setCommand(Command command)
  {
    this.command = command;
  }
  public void invokeMethod()
  {
    command.execute();
  }
}

Command Interface: Command.java

Java
1
2
3
4
5
package com.j2eereference.designPattern;
public interface Command
{
   public void execute();
}

Concrete command class: AdditionCommand.java

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.j2eereference.designPattern;
public class AdditionCommand implements Command
{
  AdditionReceiver additionReceiver;
  public AdditionCommand(AdditionReceiver additionReceiver)
  {
    this.additionReceiver = additionReceiver;
  }
  @Override
  public void execute()
{
   // TODO Auto-generated method stub
   System.out.println("Request for addition operation has been raised");
   additionReceiver.additionAction();
}
}

 

Receiver Class: AdditionReceiver

Java
1
2
3
4
5
6
7
8
9
package com.j2eereference.designPattern
 
public class AdditionReceiver
{
   public void additionAction()
   {
     System.out.println("Performing Addition operation");
   }
}

OutPut:

Request for addition operation has been raised
Performing Addition operation

RealTime Use Cases :

  • Implementation of Runnable , callable follows command design pattern
  • In Real life, when you place order in restaurant then you are client who gives command to waiter, waiter then contact the chef to prepare your order.
  • Remote control is an other good example of command design pattern as when you press On button then TV starts up and when you press Off button the it accept your request and closes the TV.

Filed Under: Design Patterns

Template Design Pattern

June 21, 2017 By j2eereference Leave a Comment

Template Design Pattern : Template design pattern comes under behavioral design pattern which provides a way to let objects communicate with each other.

In template design pattern , we have template method which defines the steps to execute an algorithm and subclasses will provide the implementation of these steps.

How to implement Template Pattern :

To implement template pattern we need to define a template method in an abstract class .Inside this method we define steps of algorithm  which are  to be implemented by subclasses .So in this way, template pattern provides a skeleton/framework to the subclasses.

Meal class: (Abstract Class)

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public abstract class Meal
{
  public final void prepareMeal()
  {
    getIngredients();
    cookingMeal();
    servingMeal();
  }
  public abstract void getIngredients();
  public abstract void cookingMeal();
  public void servingMeal() {
  System.out.println("Serving ordered meals to customers");
}
}

VegMeal : (Subclass Implementing abstract methods)

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class VegMeal extends Meal
{
  @Override
  public void getIngredients()
  {
    System.out.println("Getting Rice, Vegetable, flour and spices for veg meal preparation");
  }
  @Override
  public void cookingMeal()
  {
    System.out.println("Cooking veg meal");
  }
}

NonVegMeal : (Subclass Implementing abstract methods)

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class NonVegMeal extends Meal
{
   @Override
   public void getIngredients()
   {
     System.out.println("Getting Rice, chicken , flour and spices for non veg meal preparation");
   }
    
   @Override
   public void cookingMeal()
   {
     System.out.println("Cooking Non-Veg meal");
   }
}

TemplateDemo : (Client Class)

Java
1
2
3
4
5
6
7
8
9
10
11
public class TemplateDemo
{
    public static void main(String[] args)
    {
      Meal vegmeal = new VegMeal();
      vegmeal.prepareMeal();
 
      Meal nonvegmeal = new NonVegMeal();
      nonvegmeal.prepareMeal();
    }
}

OutPut:

Getting Rice, Vegetable, flour and spices for veg meal preparation
Cooking veg meal
Serving ordered meals to customers
Getting Rice, chicken, flour and spices for non-veg meal preparation
Cooking Non-Veg meal
Serving ordered meals to customers

In above example of the template method pattern, Meal is an abstract class with a template method defined as prepareMeal () which defines the steps (algorithm)involved in meal preparation. We declare template method as final so that it can’t be overridden by subclasses. The steps(algorithm)defined by prepareMeal () consists of three steps:getIngredients(),cookingMeal() and servingMeal().Default implementation of servingMeal () method is already given in the abstract Meal class ,so subclasses can override this implementation as it is. The getIngredients() and cookingMeal() methods are declared abstract so that subclasses need to implement them according to their need.

When to use Template Pattern:Use template pattern where you have business logic that   number of application components shared the same processes but the implementation was slightly different.

Some Use Cases:

1)In Java,Servlet class HttpServlet is an abstract class and its doGet, doPost, doPut methods are example of template method pattern usage in Java API.

2) AbstractSet and AbstractMap are example of template design pattern

3)In RealTime scenario,to construct a house architect prepares plan which consists of steps required to build house.

 

Filed Under: Design Patterns Tagged With: behavioral design pattern, Template design pattern design pattern

Proxy design pattern

June 5, 2015 By j2eereference Leave a Comment

Proxy design pattern

The proxy design pattern allows you to provide an interface to other objects by creating a wrapper class as the proxy. The wrapper class, which is the proxy, can add additional functionality to the object of interest without changing the object’s code. Here Proxy means ‘’ on behalf of’. that directly explains proxy design pattern. It is one of the simplest and straight forward design pattern. To put it in even more simplest form it is like: in attendance we give proxy for our friend in college.

As you can see it’s quite simple – the Proxy is providing a barrier between the user and the real application.

 

Picture1

 

In  the proxy pattern, a proxy class is used to control access to another class. a proxy may avoid instantiation of an object until the object is needed. This can be useful if the object requires a lot of time or resources to create.

Now let’s see an example of how to implement proxy pattern. First, we’ll create an abstract class called Thing with a basic sayHello() message that includes the date/time that the message is displayed.

Thing.java

1
2
3
4
5
6
7
8
9
package com.jrc;
import java.util.Date;
public abstract class Thing
{            
     public void sayHello()
     {                        
         System.out.println(this.getClass().getSimpleName() + " says howdy at " + new Date());
     }
}

FastThing subclasses Thing.

FastThing.java

1
2
3
4
5
6
package com.jrc;
public class FastThing extends Thing
{            
      public FastThing()
      {            }
}

SlowThing also subclasses Thing. However, its constructor takes 5 seconds to execute.

SlowThing.java

1
2
3
4
5
6
7
8
9
10
11
12
package com.jrc;
public class SlowThing extends Thing
{            
     public SlowThing()
     {
         try {        
                 Thread.sleep(5000);        
             }catch (InterruptedException e) {
                  e.printStackTrace();                        
             }            
      }
}

The Proxy class is a proxy to a SlowThing object. Since a SlowThing object takes 5 seconds to create, we’ll use a proxy to a SlowThing so that a SlowThing object is only created on demand. This occurs when the proxy’s sayHello() method is executed. It instantiates a SlowThing object if it doesn’t already exist and then calls sayHello() on the SlowThing object.

Proxy.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.jrc;
import java.util.Date;
public class Proxy
{            
        SlowThing slowThing;            
        public Proxy()
        {                        
            System.out.println("Creating proxy at " + new Date());  
        }  
        public void sayHello()
        {                        
            if (slowThing == null)
            {
               slowThing = new SlowThing();        
            }    
            slowThing.sayHello();          
        }
}

 

The ProxyDemo class demonstrates the use of our proxy. It creates a Proxy object and then creates a FastThing object and calls sayHello() on the FastThing object. Next, it calls sayHello() on the Proxy object.

ProxyDemo.java

1
2
3
4
5
6
7
8
9
10
11
package com.jrc; 
public class ProxyDemo
{            
     public static void main(String[] args)
     {                        
         Proxy proxy = new Proxy();    
        FastThing fastThing = new FastThing();            
        fastThing.sayHello();                
         proxy.sayHello();            
     } 
}

The console output of executing ProxyDemo is:

1
2
3
Creating proxy at Sat May 03 16:41:06 PDT 2008
FastThing says howdy at Sat May 03 16:41:06 PDT 2008
SlowThing says howdy at Sat May 03 16:41:11 PDT 2008

From the output, notice that creating the Proxy object and calling sayHello() on the FastThing object occurred at 16:41:06, and calling sayHello() on the Proxy object did not call sayHello() on the SlowThing object until 16:41:11. We can see that the SlowThing creation was a time-consuming process. However, this did not slow down the execution of our application until the SlowThing object was actually required. We can see here that the proxy pattern avoids the creation of time-consuming objects until they are actually needed.

The cases can be innumerable why we can use the proxy. Let’ say we need to withdraw money to make some purchase. The way we will do it is, go to an ATM and get the money, or purchase straight with a cheque. In old days when ATMs and cheques were not available, you used to get your passbook, go to bank, get withdrawal form there, stand in a queue and withdraw money. Then go to the shop where you want to make the purchase. In this way, we can say that ATM or cheque in modern times act as proxies to the Bank.

Filed Under: Design Patterns

Singleton in Clustered Environment

March 27, 2014 By j2eereference 1 Comment

What is Singleton Design Pattern?

Singleton design pattern comes into picture when we have to control the number of object instances that can be created per Class per JVM. It controls the number of instances that can be created per class. This pattern is especially used. say for example , when you want a Configuration Object that should be shared through out the entire application.  You don’t need to create many objects by reading the same configuration data. So, Singleton pattern helps you to maintain a single Configuration object for the entire application. Thus, it helps a lot in performance wise.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Singleton {
 
   private static Singleton singleton = null;
 
   /* A private Constructor to prevent access from
    * outside this class
    */
   private Singleton(){ }
 
   /* Static 'instance' method */
   public static Singleton getInstance() {
      if (singleInstance == null) {
         synchronized (Singleton.class) {
            if (singleInstance == null) {
            singleInstance = new Singleton();
            }
         }
       }  
     return singleInstance;
  }
}

In the above example, I have used double locking mechanism ( which shouldn’t be used prior to J2SE 5.0 since there are subtle bugs with statement reordering ) in the getInstance() method to prevent creation of duplication of Singleton instances since if(singleinstance == null) is not thread safe. The best way is to create the Singleton objects during deployment of the application either in a servlet configured to load on startup or using contextListeners. We have just coverd the basics of Singleton to startup with 🙂

Singleton design pattern can only make restrictions within a JVM in creation of the object. Thus, they work well till the point you have a single JVM. What about the situation where the same application is deployed across several JVM instances in a cluster. When you have a non-ditributed local singleton object in the application, you will end up having singleton object in all the nodes (JVMs)  of the cluster. The architecture of the cluster nodes  also affects the way of managing the singleton instance in it. Before we go into JVM clustering, let us first find out why do we need to go for a cluster in short.

Clustering of application servers (JVMs) gives us these advantages in running the server application. 1) High Availability 2) High Performance 3) High Fault Tolerance. Clustering involves the two important steps as follows

1 ) Load Balancing
2) Fail-over

What is Load Balancing?  As the name states, there will be a load balancer which sits between the callers and callees and distribute the load across different servers doing the same function. This is done to achieve high availability and high performance. The example for an load balancer can be F5 load balancer, webserver or just a servlet.

What is Fail-over?  Sometimes , when the caller makes a lot of requests to a particular server successively and the server is not able to handle them, it fails in between the requests. The Fail over system should detect this failure and redirect the requests to another available server instance.

 How  to manage the Singleton instance in cluster? 

I’d suggest some of the ways which come handy to manage singleton instance in the cluster.

1) Usage of Java RMI – Registering the Singleton instance in the rmi registry in a single node and provide stub in the clustered JNDI tree to make it available across all the nodes in the cluster. All the other nodes should be the RMI clients accessing this central node. The main disadvantage is the single point of failure. we can have a fail-over node for central node which also has the Singleton instance which needs to register itself to the cluster JNDI tree when there is no singleton stub registered by the central node.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import javax.naming.*;
import java.rmi.*;
 
public class RMISingletonWrapper {
private static RMISingletonWrapper instance = null;
private static String SINGLETON_JNDI_NAME = "RMISingleton";
 
public static RMISingletonWrapper getInstance() {
return instance;
}
 
// All methods in delegate the method call to the actual
// Singleton that lives on the clustered JNDI tree.
public void delegate() {
try {
RMISingleton singleton = getRMISingleton();
singleton.delegate();
} catch (Exception e) {
// Could try and recover
e.printStackTrace();
}
}
 
// Locate the true Singleton object in the cluster.
private RMISingleton getRMISingleton() {
RMISingleton rmiSingleton = null;
try {
Context jndiContext = new InitialContext();
Object obj = jndiContext.lookup(SINGLETON_JNDI_NAME);
rmiSingleton = (RMISingleton)PortableRemoteObject.narrow(
obj,
Class.forName("examples.singleton.rmi.RMISingleton"));
} catch (Exception e) {
// Could try and recover
e.printStackTrace();
}
return rmiSingleton;
}
}

 

2) Distributed Singleton Caches – As the name states, the singleton instance objects are present in all the nodes of the cluster as data caches. Since a Singleton instance exists on each container any update to the cached data by one singleton will not be synced to other singletons that exist on other containers.This issue can be resolved by the use of the Java Messaging API to send update messages between Containers. In this approach if an update is made to the cache on one Container a message is published to a JMS Topic. Each Container has a listener that subscribes to that topic and updates its Singleton cache based on the messages it receives. This approach is still difficult as you have to make sure that the updates received on each container are handled in a synchronous fashion. JMS messages also take time to process so the caches may spend some time out of sync.

In the following simplistic implementation of a distributed Cache a CacheManager Singleton holds a Map of cached items. Items to be cached are placed in a CachItem object which implements the ICacheItem interface. The CacheManager does not make any attempt to remove old items from the Cache based on any criteria like “Last Accessed Time”. SwarmCache and JBoss’s TreeCache are well-suited examples of Distributed caches in cluster

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import javax.jms.*;
 
public class CacheManager implements MessageListener {
public static CacheManager instance = null;
public static Map cache = new HashMap();
 
private TopicConnectionFactory topicConnectionFactory;
private TopicConnection topicConnection;
private TopicSession topicSession;
private Topic topic;
private TopicSubscriber topicSubscriber;
private TopicPublisher topicPublisher;
 
private final static String CONNECTION_FACTORY_JNDI_NAME =
"ConnectionFactory";
private final static String TOPIC_NAME = "TopicName";
 
public static void initInstance() {
instance = new CacheManager();
}
 
public static CacheManager getInstance() {
return instance;
}
 
public synchronized void addCacheItem(ICacheItem cacheItem) {
CacheMessage cacheMessage = new CacheMessage();
cache.put(cacheItem.getId(), cacheItem.getData());
cacheMessage.setMessageType(CacheMessage.ADD);
cacheMessage.setCacheItem(cacheItem);
sendMessage(cacheMessage);
}
 
public synchronized void modifyCacheItem(ICacheItem cacheItem) {
CacheMessage cacheMessage = new CacheMessage();
cache.put(cacheItem.getId(), cacheItem.getData());
cacheMessage.setMessageType(CacheMessage.MODIFY);
cacheMessage.setCacheItem(cacheItem);
sendMessage(cacheMessage);
}
 
public ICacheItem getCacheItem(String key) {
return (ICacheItem)cache.get(key);
}
 
private CacheManager() {
try {
InitialContext context = new InitialContext();
topicConnectionFactory = (TopicConnectionFactory)
context.lookup(CONNECTION_FACTORY_JNDI_NAME);
topicConnection = topicConnectionFactory.createTopicConnection();
topicSession = topicConnection.createTopicSession(
false, Session.AUTO_ACKNOWLEDGE);
topic = (Topic) context.lookup(TOPIC_NAME);
topicSubscriber = topicSession.createSubscriber(topic);
topicSubscriber.setMessageListener(this);
topicPublisher = topicSession.createPublisher(topic);
topicConnection.start();
} catch (Exception e) {
e.printStackTrace();
}
}
 
public void onMessage(Message message) {
try {
if (message instanceof ObjectMessage) {
ObjectMessage om = (ObjectMessage)message;
CacheMessage cacheMessage = (CacheMessage)om.getObject();
ICacheItem item = cacheMessage.getCacheItem();
interpretCacheMessage(cacheMessage);
}
} catch (JMSException jmse) {
jmse.printStackTrace();
}
}
 
private void interpretCacheMessage(CacheMessage cacheMessage) {
ICacheItem cacheItem = cacheMessage.getCacheItem();
if (cacheMessage.getMessageType()==CacheMessage.ADD) {
synchronized (this) {
cache.put(cacheItem.getId(), cacheItem.getData());
}
} else if (cacheMessage.getMessageType()==CacheMessage.MODIFY) {
synchronized (this) {
cache.put(cacheItem.getId(), cacheItem.getData());
}
}
}
 
private void sendMessage(CacheMessage cacheMessage) {
try {
Message message = topicSession.createObjectMessage(cacheMessage);
topicPublisher.publish(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}

 

3 ) Available Vendor Products ( Singleton in Cluster )

i) Terracotta / Oracle Coherance – A concept of in-memory object replication, which provides a singleton view across all JVMs. Please check out their documentations respectively

ii) JGroups – This tool is a toolkit for reliable messaging. It can be used to create clusters whose nodes can send messages to each other. It helps us in managing the Singleton instance by making use of the messaging feature across nodes.It allows to form a group and Applications (JVM’s) can participate and JGroups will send messages to everyone in the group so that they can be in sync.

The main features include

  • Cluster creation and deletion. Cluster nodes can be spread across LANs or WANs
  • Joining and leaving of clusters
  • Membership detection and notification about joined/left/crashed cluster nodes
  • Detection and removal of crashed nodes
  • Sending and receiving of node-to-cluster messages (point-to-multipoint)
  • Sending and receiving of node-to-node messages (point-to-point)

i) JBoss – HASingleton Service

A clustered singleton service is deployed on multiple nodes in a cluster but runs on only one of the nodes. The node running the singleton service is typically called the master node. When the master fails, another master is selected from the remaining nodes and the service is restarted on the new master. Please check the link to learn about JBoss clustering in detail

iv) WebLogic – Singleton Service

Weblogic has the concept of Singleton Service – where only instance runs within the cluster and all clients will look up to the same instance. Please check the link to learn about Weblogic Singleton Service

v) Websphere – ObjectGrid

WebSphere supports the concept of singleton across cluster in the WebSphere XD version of the application servers. Please check this link to learn more on Object Grid

Related Posts

  • Java Buzzwords
  • Anonymous Inner Class in Java
  • Network Programming – java.net Package
  • Java Regular Expressions
  • Method Local Inner Class in Java
  • URL Processing in Java
  • Difference between Stack and Heap memory
  • What is ThreadMXBean in java?
  • What is serialVersionUID
  • What is exchanger in concurrency?

Filed Under: Core Java, Design Patterns

  • Page 1
  • Page 2
  • Next Page »

Primary Sidebar

FOLLOW US ONLINE

  • View J2eereference-166104970118637’s profile on Facebook
  • View j2eereference’s profile on Twitter
  • View j2eereference’s profile on LinkedIn

Subscribe by email

Recent posts

  • Java Buzzwords
  • Anonymous Inner Class in Java
  • Network Programming – java.net Package
  • Java Regular Expressions
  • Method Local Inner Class in Java
  • URL Processing in Java
  • Iterator Design Pattern Implementation using Java
  • Strategy Design Pattern Implementation using Java
  • Decorator Design Pattern
  • Adapter Design Pattern Implementation using Java
  • JSF Composite Components
  • JSF UI Components
  • What is JavaServer Faces (JSF)?
  • GOF Design Patterns
  • History and Need for Design Patterns

Footer

Core Java
Design Patterns
JSP
Servlets
HTML
Building Tools
AJAX
SCJP
jQuery
Testing
Spring
UML
Struts
Java Centers
Java Training
Home
About Us
Contact Us
Copyright © j2eereference.com. All right reserved.