0
488views
i need to Implement at least five design patterns in java

i need to Implement at least five design patterns in java ( Singleton, Factory, Façade, state,staratege) in the application. How can I do it

1 Answer
0
2views

Singleton Pattern

  • Singleton pattern is the simplest design pattern in Java that come under the Creational Pattern Category.
  • This pattern involves a single class that is responsible to create an object while making sure that only a single object gets created.
  • This class provides a way to access its only object which can be accessed directly without the need to instantiate the object of the class.

IMPLEMENTATION:

Step 1 - Create a Singleton Class.

SingletonObject.java

class SingletonObject {
   //create an object of SingletonObject
   private static SingletonObject instance = new SingletonObject();

   //private constructor so that we cannot instantiate the class
   private SingletonObject(){}

   //returns the only available object
   public static SingletonObject getInstance(){
      return instance;
   }

   public void printMessage(){
      System.out.println("Hello from Singleton object!!!");
   }
}

Step 2 - Get the only object from the singleton class.

Main.java

public class Main {
   public static void main(String[] args) {

      //illegal statement because constructor is private
      //Compile Time Error: The constructor SingletonObject() is not visible
      //SingletonObject object = new SingletonObject();

      //call getInstance to retrieve the object available from the class
      SingletonObject object = SingletonObject.getInstance();

      //show the message
      object.printMessage();
   }
}

OUTPUT:

Hello from Singleton object!!!

Factory Pattern

  • Factory pattern is mostly used design patterns in Java that comes under the Creational Pattern Category. This pattern provides the best ways to create an object.
  • In the Factory pattern, an object is created without exposing the creation logic to the client and refers to a newly created object using a common interface.

IMPLEMENTATION:

Step 1 - Create an interface.

Geometric_shape.java

//Geometric_shape interface

public interface Geometric_shape {
   void draw_shape();
}

Step 2 - Create concrete classes implementing the same interface.

Rectangle.java

//Geometric shape classes implementing Geometric_shape interface

public class Rectangle implements Geometric_shape {
   @Override
   public void draw_shape() {
      System.out.println("Rectangle class::draw_shape() method.");
   }
}

Square.java

//Geometric shape classes implementing Geometric_shape interface

public class Square implements Geometric_shape {
   @Override
   public void draw_shape() {
      System.out.println("Square class::draw_shape() method.");
   }
}

Circle.java

//Geometric shape classes implementing Geometric_shape interface

public class Circle implements Geometric_shape {
   @Override
   public void draw_shape() {
      System.out.println("Circle class::draw_shape() method.");
   }
}

Step 3 - Create a Factory to generate an object of concrete class based on given information.

ShapeFactory.java

//Factory class for Geometric_shape

public class ShapeFactory {
   //shapeObject method gets  particular shapeType (circle, Square or Rectangle)
   public Geometric_shape shapeObject(String shapeType){
      if(shapeType == null){
         return null;
      } 
      //retrieve Circle object
      if(shapeType.equalsIgnoreCase("Circle")){
         return new Circle();

      //retrieve Rectangle object     
      } else if(shapeType.equalsIgnoreCase("Rectangle")){
         return new Rectangle();

      ////retrieve Square object     
      } else if(shapeType.equalsIgnoreCase("Square")){
         return new Square();
      }
      return null;
   }
}

Step 4 - Use the Factory to get an object of the concrete class by passing a piece of information such as type.

Main.java

public class Main {

   public static void main(String[] args) {
      //Create a ShapeFactory object to get different geometric shapes
      ShapeFactory shapeFactory = new ShapeFactory();

      //circle
      Geometric_shape shape_Circle = shapeFactory.shapeObject("CIRCLE");

      //draw method of Circle
      shape_Circle.draw_shape();

      //Rectangle
      Geometric_shape shape_Rectangle = shapeFactory.shapeObject("RECTANGLE");

      //draw method of Rectangle
      shape_Rectangle.draw_shape();

      //Square
      Geometric_shape shape_Square = shapeFactory.shapeObject("SQUARE");

      //draw method of square
      shape_Square.draw_shape();
   }
}

OUTPUT:

Circle class::draw_shape() method.

Rectangle class::draw_shape() method.

Square class::draw_shape() method.

Façade Pattern

  • This java pattern comes under the Structural Design Pattern Category.
  • Facade pattern hides the complexities of the system and provides an interface to the client using which the client can access the system.
  • To do this façade pattern adds an interface to an existing system to hide its complexities.
  • This pattern involves a single class that provides simplified methods required by the client and delegates calls to methods of existing system classes.

IMPLEMENTATION:

Step 1 - Create an interface.

Geometric_shape.java

//Geometric_shape interface

public interface Geometric_shape {
   void draw_shape();
}

Step 2 - Create concrete classes implementing the same interface.

Rectangle.java

//Geometric shape classes implementing Geometric_shape interface

public class Rectangle implements Geometric_shape {
   @Override
   public void draw_shape() {
      System.out.println("Rectangle::draw_shape()");
   }
}

Square.java

//Geometric shape classes implementing Geometric_shape interface

public class Square implements Geometric_shape {
   @Override
   public void draw_shape() {
      System.out.println("Square::draw_shape()");
   }
}

Circle.java

//Geometric shape classes implementing Geometric_shape interface

public class Circle implements Geometric_shape {
   @Override
   public void draw_shape() {
      System.out.println("Circle::draw_shape()");
   }
}

Step 3 - Create a facade class.

ShapeMaker.java

// Façade class for Geometric_shape

public class ShapeMaker {
   private Shape circle;
   private Shape rectangle;
   private Shape square;

   public ShapeMaker() {
      circle = new Circle();
      rectangle = new Rectangle();
      square = new Square();
   }

   public void drawCircle(){
      circle.draw_shape();
   }
   public void drawRectangle(){
      rectangle.draw_shape();
   }
   public void drawSquare(){
      square.draw_shape();
   }
}

Step 4 - Use the facade to draw various types of shapes.

Main.java

public class Main {
   public static void main(String[] args) {
      //Create a ShapeMaker object to get different geometric shapes
      ShapeMaker shapeMaker = new ShapeMaker();

      shapeMaker.drawCircle();
      shapeMaker.drawRectangle();
      shapeMaker.drawSquare();      
   }
}

OUTPUT:

Circle::draw_shape()

Rectangle::draw_shape()

Square::draw_shape()

State Pattern

  • This java pattern comes under the Behavioral Design Pattern Category.
  • In a State pattern a class behavior changes according to its state.
  • In a State pattern, created objects represent various states and a context object whose behavior varies as its state object changes.

IMPLEMENTATION:

Step 1 – Create an interface.

State.java

// State interface

public interface State {
   public void doAction(Context context);
}

Step 2 - Create concrete classes implementing the same interface.

StartState.java

//State classes implementing State interface

public class StartState implements State {

   public void doAction(Context context) {
      System.out.println("The Player is in the start state");
      context.setState(this);   
   }

   public String toString(){
      return "Start State";
   }
}

StopState.java

//State classes implementing State interface

public class StopState implements State {

   public void doAction(Context context) {
      System.out.println("The Player is in the stop state");
      context.setState(this);   
   }

   public String toString(){
      return "Stop State";
   }
}

Step 3 - Create Context Class.

Context.java

public class Context {
   private State state;

   public Context(){
      state = null;
   }

   public void setState(State state){
      this.state = state;       
   }

   public State getState(){
      return state;
   }
}

Step 4 – Use the Context to see the behavior change when the State changes.

Main.java

public class Main {
   public static void main(String[] args) {
      //Create a Context object to get different states of the player

      Context context = new Context();

      //start state
      StartState startState = new StartState();
      startState.doAction(context);

      System.out.println(context.getState().toString());

      //stopstate
      StopState stopState = new StopState();
      stopState.doAction(context);

      System.out.println(context.getState().toString());
   }
}

OUTPUT:

The Player is in the start state

Start State

The Player is in the stop state

Stop State

Strategy Pattern

  • This java pattern comes under the Behavioral Design Pattern Category.
  • In a Strategy pattern, a class behavior or its algorithm can be changed at run time.
  • In the Strategy pattern, created objects represent various strategies and a context object whose behavior varies as per its strategy object.
  • The strategy object changes the executing algorithm of the context object.

IMPLEMENTATION:

Step 1 - Create an interface.

Strategy.java

// Strategy interface

public interface Strategy {
   public int doOperation(int num1, int num2);
}

Step 2 - Create concrete classes implementing the same interface.

OperationAdd.java

//Strategy classes implementing Strategy interface

public class OperationAdd implements Strategy{
   @Override
   public int doOperation(int num1, int num2) {
      return num1 + num2;
   }
}

OperationSubstract.java

//Strategy classes implementing Strategy interface

public class OperationSubstract implements Strategy{
   @Override
   public int doOperation(int num1, int num2) {
      return num1 - num2;
   }
}

OperationMultiply.java

//Strategy classes implementing Strategy interface

public class OperationMultiply implements Strategy{
   @Override
   public int doOperation(int num1, int num2) {
      return num1 * num2;
   }
}

Step 3 - Create Context Class.

Context.java

public class Context {
   private Strategy strategy;

   public Context(Strategy strategy){
      this.strategy = strategy;
   }

   public int executeStrategy(int num1, int num2){
      return strategy.doOperation(num1, num2);
   }
}

Step 4 – Use the Context to see the behavior change when it changes its Strategy.

Main.java

public class Main {
   public static void main(String[] args) {
      Context context = new Context(new OperationAdd());        
      System.out.println("Addition of 23 + 14 = " + context.executeStrategy(23, 14));

      context = new Context(new OperationSubstract());      
      System.out.println("Subtraction of 23 - 14 = " + context.executeStrategy(23, 14));

      context = new Context(new OperationMultiply());       
      System.out.println("Multiplication of 23 * 14 = " + context.executeStrategy(23, 14));
   }
}

OUTPUT:

Addition of 23 + 14 = 37

Subtraction of 23 - 14 = 9

Multiplication of 23 * 14 = 322

Please log in to add an answer.