Related differences

Ques 11. What is Prototype Design Pattern in java design patterns?

Prototype pattern refers to creating duplicate object while keeping performance in mind. This type of design pattern comes under creational pattern as this pattern provides one of the best way to create an object.

This pattern involves implementing a prototype interface which tells to create a clone of the current object. This pattern is used when creation of object directly is costly. For example, a object is to be created after a costly database operation. We can cache the object, returns its clone on next request and update the database as as and when needed thus reducing database calls.

We're going to create an abstract class Mobile and concrete classes extending the Mobile class. A class MobileCache is defined as a next step which stores shape objects in a Hashtable and returns their clone when requested.

PrototypPatternDemo, our demo class will use MobileCache class to get a Mobile object.

Step 1
Create an abstract class implementing Clonable interface.
Mobile.java
public abstract class Mobile implements Cloneable {
   
   private String id;
   protected String type;
   
   abstract void make();
   
   public String getType(){
      return type;
   }
   
   public String getId() {
      return id;
   }
   
   public void setId(String id) {
      this.id = id;
   }
   
   public Object clone() {
      Object clone = null;
      try {
         clone = super.clone();
      } catch (CloneNotSupportedException e) {
         e.printStackTrace();
      }
      return clone;
   }
}

Step 2
Create concrete classes extending the above class.
Sony.java
public class Sony extends Mobile {

   public Sony(){
     type = "Sony";
   }

   @Override
   public void make() {
      System.out.println("Inside Sony::make() method.");
   }
}

Blackberry.java
public class Blackberry extends Mobile {

   public Blackberry(){
     type = "Blackberry";
   }

   @Override
   public void make() {
      System.out.println("Inside Blackberry::make() method.");
   }
}

Samsung.java
public class Samsung extends Mobile {

   public Samsung(){
     type = "Samsung";
   }

   @Override
   public void make() {
      System.out.println("Inside Samsung::make() method.");
   }
}

Step 3
Create a class to get concreate classes from database and store them in a Hashtable.
MobileCache.java
import java.util.Hashtable;
public class MobileCache {
   private static Hashtable<String, Mobile> shapeMap 
      = new Hashtable<String, Mobile>();

   public static Mobile getMobile(String shapeId) {
      Mobile cachedMobile = shapeMap.get(shapeId);
      return (Mobile) cachedMobile.clone();
   }

   // for each shape run database query and create shape
   // shapeMap.put(shapeKey, shape);
   // for example, we are adding three shapes
   public static void loadCache() {
      Samsung circle = new Samsung();
      circle.setId("1");
      shapeMap.put(circle.getId(),circle);

      Blackberry square = new Blackberry();
      square.setId("2");
      shapeMap.put(square.getId(),square);

      Sony rectangle = new Sony();
      rectangle.setId("3");
      shapeMap.put(rectangle.getId(),rectangle);
   }
}

Step 4
PrototypePatternDemo uses MobileCache class to get clones of shapes stored in a Hashtable.
PrototypePatternDemo.java
public class PrototypePatternDemo {
   public static void main(String[] args) {
      MobileCache.loadCache();

      Mobile clonedMobile = (Mobile) MobileCache.getMobile("1");
      System.out.println("Mobile : " + clonedMobile.getType());

      Mobile clonedMobile2 = (Mobile) MobileCache.getMobile("2");
      System.out.println("Mobile : " + clonedMobile2.getType());

      Mobile clonedMobile3 = (Mobile) MobileCache.getMobile("3");
      System.out.println("Mobile : " + clonedMobile3.getType());
   }
}

Step 5
Verify the output.
Mobile : Samsung
Mobile : Blackberry
Mobile : Sony

Is it helpful? Add Comment View Comments
 

Ques 12. What is Decorator Design Pattern in java design patterns?

Decorator pattern allows to add new functionality an existing object without altering its structure. This type of design pattern comes under structural pattern as this pattern acts as a wrapper to existing class.

This pattern creates a decorator class which wraps the original class and provides additional functionality keeping class methods signature intact.

We are demonstrating use of Decorator pattern via following example in which we'll decorate a shape with some color without alter shape class.

We're going to create a Mobile interface and concrete classes implementing the Mobile interface. We then create a abstract decorator class MobileDecorator implementing the Mobile interface and having Mobile object as its instance variable.

RedMobileDecorator is concrete class implementing MobileDecorator.
DecoratorPatternDemo, our demo class will use RedMobileDecorator to decorate Mobile objects.

Step 1
Create an interface.
Mobile.java
public interface Mobile {
   void make();
}

Step 2
Create concrete classes implementing the same interface.
Sony.java
public class Sony implements Mobile {

   @Override
   public void make() {
      System.out.println("Mobile: Sony");
   }
}

Blackberry.java
public class Blackberry implements Mobile {

   @Override
   public void make() {
      System.out.println("Mobile: Blackberry");
   }
}

Step 3
Create abstract decorator class implementing the Mobile interface.
MobileDecorator.java
public abstract class MobileDecorator implements Mobile {
   protected Mobile decoratedMobile;

   public MobileDecorator(Mobile decoratedMobile){
      this.decoratedMobile = decoratedMobile;
   }

   public void make(){
      decoratedMobile.make();
   }
}

Step 4
Create concrete decorator class extending the MobileDecorator class.
RedMobileDecorator.java
public class RedMobileDecorator extends MobileDecorator {

   public RedMobileDecorator(Mobile decoratedMobile) {
      super(decoratedMobile);
   }

   @Override
   public void make() {
      decoratedMobile.make();       
      setRedBorder(decoratedMobile);
   }

   private void setRedBorder(Mobile decoratedMobile){
      System.out.println("Border Color: Red");
   }
}

Step 5
Use the RedMobileDecorator to decorate Mobile objects.
DecoratorPatternDemo.java
public class DecoratorPatternDemo {
   public static void main(String[] args) {

      Mobile circle = new Blackberry();

      Mobile redBlackberry = new RedMobileDecorator(new Blackberry());

      Mobile redSony = new RedMobileDecorator(new Sony());
      System.out.println("Blackberry with normal border");
      circle.make();

      System.out.println("nBlackberry of red border");
      redBlackberry.make();

      System.out.println("nSony of red border");
      redSony.make();
   }
}

Step 6
Verify the output.

Blackberry with normal border
Mobile: Blackberry

Blackberry of red border
Mobile: Blackberry
Border Color: Red

Sony of red border
Mobile: Sony
Border Color: Red

Is it helpful? Add Comment View Comments
 

Ques 13. What is Observer Design Pattern in java design patterns?

Observer pattern is used when there is one to many relationship between objects such as if one object is modified, its depenedent objects are to be notified automatically. Observer pattern falls under behavioral pattern category.

Observer pattern uses three actor classes. Subject, Observer and Client. Subject, an object having methods to attach and de-attach observers to a client object. We've created classes Subject, Observer abstract class and concrete classes extending the abstract class the Observer.

ObserverPatternDemo, our demo class will use Subject and concrete class objects to show observer pattern in action.

Step 1
Create Subject class.
Subject.java
import java.util.ArrayList;
import java.util.List;
public class Subject {
   private List<Observer> observers 
      = new ArrayList<Observer>();
   private int state;

   public int getState() {
      return state;
   }

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

   public void attach(Observer observer){
      observers.add(observer);
   }

   public void notifyAllObservers(){
      for (Observer observer : observers) {
         observer.update();
      }
   }
}

Step 2
Create Observer class.
Observer.java
public abstract class Observer {
   protected Subject subject;
   public abstract void update();
}

Step 3
Create concrete observer classes
BinaryObserver.java
public class BinaryObserver extends Observer{
   public BinaryObserver(Subject subject){
      this.subject = subject;
      this.subject.attach(this);
   }

   @Override
   public void update() {
      System.out.println( "Binary String: " 
      + Integer.toBinaryString( subject.getState() ) ); 
   }
}

OctalObserver.java
public class OctalObserver extends Observer{
   public OctalObserver(Subject subject){
      this.subject = subject;
      this.subject.attach(this);
   }

   @Override
   public void update() {
     System.out.println( "Octal String: " 
     + Integer.toOctalString( subject.getState() ) ); 
   }
}

HexaObserver.java
public class HexaObserver extends Observer{
   public HexaObserver(Subject subject){
      this.subject = subject;
      this.subject.attach(this);
   }

   @Override
   public void update() {
      System.out.println( "Hex String: " 
      + Integer.toHexString( subject.getState() ).toUpperCase() ); 
   }
}

Step 4
Use Subject and concrete observer objects.
ObserverPatternDemo.java
public class ObserverPatternDemo {
   public static void main(String[] args) {
      Subject subject = new Subject();

      new HexaObserver(subject);
      new OctalObserver(subject);
      new BinaryObserver(subject);

      System.out.println("First state change: 15");
      subject.setState(15);
      System.out.println("Second state change: 10");
      subject.setState(10);
   }
}

Step 5
Verify the output:
First state change: 15
Hex String: F
Octal String: 17
Binary String: 1111
Second state change: 10
Hex String: A
Octal String: 12
Binary String: 1010

Is it helpful? Add Comment View Comments
 

Ques 14. What is MVC design pattern in java design patterns?

MVC Pattern stands for Model-View-Controller Pattern. This pattern is used to separate application's concerns.
Model - Model represents an object or JAVA POJO carrying data. It can also have logic to update controller if its data changes.
View - View represents the visualization of the data that model contains.
Controller - Controller acts on both Model and view. It controls the data flow into model object and updates the view whenever data changes. It keeps View and Model separate.

We're going to create a Employee object acting as a model.EmployeeView will be a view class which can print employee details on console and EmployeeController is the controller class responsible to store data in Employee object and update view EmployeeView accordingly.
MVCPatternDemo, our demo class will use EmployeeController to demonstrate use of MVC pattern.

Step 1
Create Model.
Employee.java
public class Employee {
   private String salary;
   private String name;
   public String getSalary() {
      return salary;
   }
   public void setSalary(String salary) {
      this.salary = salary;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}

Step 2
Create View.
EmployeeView.java
public class EmployeeView {
   public void printEmployeeDetails(String employeeName, String employeeSalary){
      System.out.println("Employee: ");
      System.out.println("Name: " + employeeName);
      System.out.println("Salary: " + employeeSalary);
   }
}

Step 3
Create Controller.
EmployeeController.java
public class EmployeeController {
   private Employee model;
   private EmployeeView view;

   public EmployeeController(Employee model, EmployeeView view){
      this.model = model;
      this.view = view;
   }

   public void setEmployeeName(String name){
      model.setName(name);
   }

   public String getEmployeeName(){
      return model.getName();
   }

   public void setEmployeeSalary(String salary){
      model.setSalary(salary);
   }

   public String getEmployeeSalary(){
      return model.getSalary();
   }

   public void updateView(){
      view.printEmployeeDetails(model.getName(), model.getSalary());
   }
}

Step 4
Use the EmployeeController methods to demonstrate MVC design pattern usage.
MVCPatternDemo.java
public class MVCPatternDemo {
   public static void main(String[] args) {

      //fetch employee record based on his roll no from the database
      Employee model  = retriveEmployeeFromDatabase();

      //Create a view : to write employee details on console
      EmployeeView view = new EmployeeView();

      EmployeeController controller = new EmployeeController(model, view);

      controller.updateView();

      //update model data
      controller.setEmployeeName("Craig");

      controller.updateView();
   }

   private static Employee retriveEmployeeFromDatabase(){
      Employee employee = new Employee();
      employee.setName("Maxwell");
      employee.setSalary("30000");
      return employee;
   }
}

Step 5
Verify the output:
Employee: 
Name: Maxwell
Salary: 30000
Employee: 
Name: Kate
Salary: 30000

Is it helpful? Add Comment View Comments
 

Ques 15. What is builder pattern and give an example.

Builder pattern builds a complex object using simple objects and using a step by step approach. It creates one by one object and wraps on parent object. E.g. burger making, pizza making, house building etc.

Below we have created a Pizza restaurant where pizza and cold-drink is a typical meal. Pizza can be Italian, American, Mexican etc which will be packed in a wrapper and Cold-drink can be Pepsi, Coke, Limca etc which will be packed in a bottle.

Creating an Item interface representing food items such as pizzas and cold drinks and concrete classes implementing the Item interface and a Packing interface representing packaging of food items and concrete classes implementing the Packing interface as burger would be packed in wrapper and cold drink would be packed as bottle.

We then create a Meal class having ArrayList of Item and a MealBuilder to build different types of Meal object by combining Item. BuilderPatternDemo, our demo class will use MealBuilder to build a Meal.

Step 1
Create an interface Item representing food item and packing.
Item.java
public interface Item {
   public String name();
   public Packing packing();
   public float price();
}

Packing.java
public interface Packing {
   public String pack();
}

Step 2
Create concreate classes implementing the Packing interface.
Wrapper.java
public class Wrapper implements Packing {

   @Override
   public String pack() {
      return "Wrapper";
   }
}

Bottle.java
public class Bottle implements Packing {
   @Override
   public String pack() {
      return "Bottle";
   }
}

Step 3
Create abstract classes implementing the item interface providing default functionalities.
Pizza.java
public abstract class Pizza implements Item {

   @Override
   public Packing packing() {
      return new Wrapper();
   }
   @Override
   public abstract float price();
}

ColdDrink.java
public abstract class ColdDrink implements Item {
@Override
public Packing packing() {
       return new Bottle();
}
@Override
public abstract float price();
}

Step 4
Create concrete classes extending Pizza and ColdDrink classes
ItalianPizza.java
public class ItalianPizza extends Pizza {
   @Override
   public float price() {
      return 200.0f;
   }
   @Override
   public String name() {
      return "Italian Pizza";
   }
}

AmericanPizza.java
public class AmericanPizza extends Pizza {
   @Override
   public float price() {
      return 300.0f;
   }
   @Override
   public String name() {
      return "American Pizza";
   }
}

Coke.java
public class Coke extends ColdDrink {
   @Override
   public float price() {
      return 30.0f;
   }
   @Override
   public String name() {
      return "Coke";
   }
}

Pepsi.java
public class Pepsi extends ColdDrink {
   @Override
   public float price() {
      return 40.0f;
   }
   @Override
   public String name() {
      return "Pepsi";
   }
}

Step 5
Create a Meal class having Item objects defined above.
Meal.java
import java.util.ArrayList;
import java.util.List;
public class Meal {
   private List<Item> items = new ArrayList<Item>();
   public void addItem(Item item){
      items.add(item);
   }
   public float getCost(){
      float cost = 0.0f;
      for (Item item : items) {
         cost += item.price();
      }
      return cost;
   }
   public void showItems(){
      for (Item item : items) {
         System.out.print("Item : "+item.name());
         System.out.print(", Packing : "+item.packing().pack());
         System.out.println(", Price : "+item.price());
      }
   }
}

Step 6
Create a MealBuilder class, the actual builder class responsible to create Meal objects.
MealBuilder.java
public class MealBuilder {
   public Meal prepareVegMeal (){
      Meal meal = new Meal();
      meal.addItem(new ItalianPizza());
      meal.addItem(new Coke());
      return meal;
   }   
   public Meal prepareNonVegMeal (){
      Meal meal = new Meal();
      meal.addItem(new AmericanPizza());
      meal.addItem(new Pepsi());
      return meal;
   }
}

Step 7
BuiderPatternDemo uses MealBuider to demonstrate builder pattern.
BuilderPatternDemo.java
public class BuilderPatternDemo {
   public static void main(String[] args) {
      MealBuilder mealBuilder = new MealBuilder();
      Meal vegMeal = mealBuilder.prepareVegMeal();
      System.out.println("Veg Meal");
      vegMeal.showItems();
      System.out.println("Total Cost: " +vegMeal.getCost());
      Meal nonVegMeal = mealBuilder.prepareNonVegMeal();
      System.out.println("nnNon-Veg Meal");
      nonVegMeal.showItems();
      System.out.println("Total Cost: " +nonVegMeal.getCost());
   }
}

Step 8
Verify the output.
Veg Meal
Item : Italian Pizza, Packing : Wrapper, Price : 200.0
Item : Coke, Packing : Bottle, Price : 30.0
Total Cost: 230.0

Non-Veg Meal
Item : American Pizza, Packing : Wrapper, Price : 300.0
Item : Pepsi, Packing : Bottle, Price : 40.0
Total Cost: 340.0

Is it helpful? Add Comment View Comments
 

Most helpful rated by users: