Showing posts with label OOPS. Show all posts
Showing posts with label OOPS. Show all posts

Sunday, October 6

Builder Design Pattern

What is builder design pattern ?

This is used to segregate the logic for creation of complex objects. 

For example

 If we want to create an object of class representing real Estate residential project . We need to take into account lot of factors in building full fledged object . Object will consist of features like 
 payment plan 
layout 
construction plan 
builder information 
land details 
finance details 
location details
salient features 

and so on.....




So we won't prefer to embed the logic of creation of this instance in actual business logic and unnecessarily clutter the business logic flow Instead It would be good to have a dedicated service which can build up this object and once prepared can return it to business logic . Thus actual business logic remains agnostic of all object creation complexities..

So how do we achieve that in Object oriented language . 


Let us try to understand this with code. As usual I have written lot of System.out.println statements in the code to bring are execution flow steps in print statements . This code can be directly copied and executed .All steps of design pattern will be clearly written on console.


-----------------------------------------------------------------------------------------------

//This is the Client class which basically place an order. Here this client first place an order of //commercial project and after it's successful delivery It approaches for residential project and //place an order for that.



package realEstate;

public class Client {

    /**
     * @param args
     */
    public static void main(String[] args) {
      
        projectOwner owner=new projectOwner(new CommercialProjectBuilder());
        owner.placeRoder();
        owner.getProject();
        System.out.println("CLIENT :::: Thank you for timely delivry of commerical project");
        System.out.println("===============================================================");
        System.out.println("CLIENT :::: Now let's deal in residenrial");
         owner=new projectOwner(new ResidentialProjectBuilder());
        owner.placeRoder();
        owner.getProject();
        System.out.println("CLIENT :::: Thank you for timely delivry of Residential project.. Rocking performance");
    }

}

// This is project Owner . Client passes the type of project It is looking for : commercial or residential //and creates Project Owner instance . Owner will further place order of construction to Commercial //or Residential department based of which object is passed by client 
class projectOwner{
    ProjectBuiding building;
    projectOwner(ProjectBuiding building){
        this.building=building;
        }
   
  void  placeRoder(){
      building.constructBase();
      building.constructFloors();
      building.doFinishing();
      building.decorate();

   }
 
  ProjectBuiding  getProject(){
      return building;
  }
  
   
}

// Interface for Residential and commercial project builder classes 
interface ProjectBuiding{
   
   
   
    void constructBase();
   
    void constructFloors();
   
    void doFinishing();
   
    void decorate();
   
   
}

// entire process and logic of building a residential project is encapsulated in this class
class ResidentialProjectBuilder implements ProjectBuiding {
   
    ResidentialProjectBuilder(){
        System.out.println("ResidentialProjectBuilder:::Thank you for reaching us..We deal in Residential Projects..");
    }

    public void constructBase() {
      
        System.out.println("ResidentialProjectBuilder:::Construction is already started.. Promise to deliver on time ");
    }

    public void constructFloors() {
        System.out.println("ResidentialProjectBuilder::::Construction is on full Swing.. Pay installments timely ");
       
    }

    public void doFinishing() {
        System.out.println("ResidentialProjectBuilder::::About to deliver .. Have litte more Patience ");
       
    }

    public void decorate() {
        System.out.println("ResidentialProjectBuilder:::IT is well decorated.. Ready to move");
       
    }
   
}


// entire process and logic of building a Commercial project is encapsulated in this class


class CommercialProjectBuilder implements ProjectBuiding{

    CommercialProjectBuilder(){
        System.out.println("CommercialProjectBuilder ::: Thank you for reaching us..We deal in Commercial Projects..");
    }
   
    public void constructBase() {
        System.out.println("CommercialProjectBuilder :::Construction is already started.. Promise to deliver on time ..");
       
    }

    public void constructFloors() {
        System.out.println("CommercialProjectBuilder :::Construction is on full Swing.. Pay installments timely ");
       
    }

    public void doFinishing() {
        System.out.println("CommercialProjectBuilder :::About to deliver .. Have litte more Patience ");
       
    }

    public void decorate() {
        System.out.println("CommercialProjectBuilder :::IT is well decorated.. Ready to move");
       
    }
   
}


 Below would be the output of console on program execution
-------------------------------------------------------------------------------------------










CommercialProjectBuilder ::: Thank you for reaching us..We deal in Commercial Projects..
CommercialProjectBuilder :::Construction is already started.. Promise to deliver on time ..
CommercialProjectBuilder :::Construction is on full Swing.. Pay installments timely
CommercialProjectBuilder :::About to deliver .. Have litte more Patience
CommercialProjectBuilder :::IT is well decorated.. Ready to move
CLIENT :::: Thank you for timely delivry of commerical project

===============================================================



CLIENT :::: Now let's deal in residenrial
ResidentialProjectBuilder:::Thank you for reaching us..We deal in Residential Projects..
ResidentialProjectBuilder:::Construction is already started.. Promise to deliver on time
ResidentialProjectBuilder::::Construction is on full Swing.. Pay installments timely
ResidentialProjectBuilder::::About to deliver .. Have litte more Patience
ResidentialProjectBuilder:::IT is well decorated.. Ready to move
CLIENT :::: Thank you for timely delivry of Residential project.. Rocking performance

 


-->

Saturday, September 28

Visitor Design pattern in java

                                             Visitor Design pattern in java

Think from a visitors perspective for a while ---

A person comes from US to visit India ... 

Visitor want to visit certain places .. He has the list of places he want to visit . 

So he provide the same list to his travel organizer and ask him to prepare a suitable plan for him to make him travel all the places available in the list.

Organizer takes the list and start contacting his site contact persons . He ask his agents at all places visitor want to visit to accept and welcome the visitor and make him Visit the place. 

So here entire task is divided in to few sub tasks :

1. Visitor -- Ask visitor to plan . Visit the places.
2. Organizer -- activate his place specific agents 
3. Place agents --- Accept the visitor and make him Visit. 





Now lets understand this scenario in Object oriented world of java technology . How design pattern deals with this situation.

As usual , I would be providing all steps involved in the process in system.out.println statements. Code below can be copied as it is and executed in any java environment . System.out,print statements will print all the steps involved in process on console as well


==============================================

Visitor class represents the visitor . He creates the list of places to be visited and invoke schedule method on organizer . Before invoking schedule method Visitor creates instance of Organizer and while constructing instance it uses one argument constructor to initiate Organizer instance with a state having list of Place instances.



package incredibleIndia;

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

public class Visitor implements IVisotor {

    /**
     * @param args
     */
    public static void main(String[] args) {
        List places = new ArrayList();
        places.add(new IndiaGate());
        places.add(new Tajmahal());
        places.add(new BirSujra());
        places.add(new RedFort());
        places.add(new JamaMasjid());
        Organizer org = new Organizer(places);
        System.out
                .println("Visitor ask Organizer to plan for his visit. Visitor provides Organizer the list of places he is interested in ");
        org.schedule(new Visitor());
       
        System.out.println("Visotor Thanks  all .. It wwas wondeful experience... truely incredible India");

    }

    public void visit(IndiaGate india) {
        System.out.println("visitng india gate.....");

    }

    public void visit(Tajmahal india) {
        System.out.println("visitng Tajmahal.....");

    }

    public void visit(BirSujra birSujra) {
        System.out.println("visitng birSujra.....");

    }

    public void visit(RedFort redFort) {
        System.out.println("visitng RedFort....");

    }

    public void visit(JamaMasjid jamaMasjid) {
        System.out.println("visitng JamaMasjid....");

    }

}

This is contract interface which is helping Visitor to visit the places available in the list. Visitor implements this interface and implement are overloaded methods each referring to one single element /place 
interface IVisotor {

    void visit(IndiaGate indiaGate);

    void visit(Tajmahal tajMahal);

    void visit(BirSujra birsujra);

    void visit(RedFort redFort);

    void visit(JamaMasjid jamaMasjid);
}

This is interface for Organizer to implement . It has only schedule method

interface IOrganize {

    public void schedule(IVisotor visitor);

}

Organizer takes the list of places in constructor . In schedule method It iterates over Place instances and invoke their accept method to make the places accept the visitor . in accept() method it passes the Visitor as parameter. Each Place instance being iterated here refer to once actual Place / class implementing Place interface
class Organizer implements IOrganize {
    List places = new ArrayList();

    public Organizer(List places) {
        this.places = places;
    }

    public void schedule(IVisotor visitor) {

        System.out
                .println("Organizer get through the process to initiate the visit and ask place coordinators to welcomes the visitor  ");

        for (Place place : places) {
            place.accept(visitor);
        }

    }

}

Interface for place . Has only one method . Accept . This needs to be implemented by all Place classes
interface Place {

    void accept(IVisotor visitor);

}

One of the class implementing Place interface and defining the logic of accept method . Accept method will accept the visitor and then on visitor instance invoke visit method and pass the current place instance to the visitor . Visitor can use this instance to visit the place 

class IndiaGate implements Place {

    public void accept(IVisotor visitor) {

        System.out.println("IndiaGate accept the visotr and welcomes him");

        System.out.println("IndiaGate visit is started");
        visitor.visit(this);
    }

}


One of the class implementing Place interface and defining the logic of accept method . Accept method will accept the visitor and then on visitor instance invoke visit method and pass the current place instance to the visitor . Visitor can use this instance to visit the place 


class Tajmahal implements Place {

    public void accept(IVisotor visitor) {

        System.out.println("Tajmahal accept the visotr and welcomes him");

        System.out.println("Tajmahal visit is started");
        visitor.visit(this);
    }

}


One of the class implementing Place interface and defining the logic of accept method . Accept method will accept the visitor and then on visitor instance invoke visit method and pass the current place instance to the visitor . Visitor can use this instance to visit the place 


class RedFort implements Place {

    public void accept(IVisotor visitor) {
        System.out.println("RedFort accept the visotr and welcomes him");

        System.out.println("RedFort visit is started");
        visitor.visit(this);
    }

}



-->


One of the class implementing Place interface and defining the logic of accept method . Accept method will accept the visitor and then on visitor instance invoke visit method and pass the current place instance to the visitor . Visitor can use this instance to visit the place 


class JamaMasjid implements Place {

    public void accept(IVisotor visitor) {
        System.out.println("JamaMasjid accept the visotr and welcomes him");

        System.out.println("JamaMasjid visit is started");
        visitor.visit(this);
    }

}


One of the class implementing Place interface and defining the logic of accept method . Accept method will accept the visitor and then on visitor instance invoke visit method and pass the current place instance to the visitor . Visitor can use this instance to visit the place 


class BirSujra implements Place {

    public void accept(IVisotor visitor) {
        System.out.println("BirSujra accept the visotr and welcomes him");

        System.out.println("BirSujra visit is started");

        visitor.visit(this);
    }

}








 Now let us see the output of console
 -------------------------------------------------------------------------------
Visitor ask Organizer to plan for his visit. Visitor provides Organizer the list of places he is interested in 


Organizer get through the process to initiate the visit and ask place coordinators to welcomes the visitor  


IndiaGate accept the visotr and welcomes him
 IndiaGate visit is started

 visiting india gate.....


Tajmahal accept the visotr and welcomes him

Tajmahal visit is started
 visiting Tajmahal.....


BirSujra accept the visotr and welcomes him

BirSujra visit is started
 visitng birSujra.....


RedFort accept the visotr and welcomes him

RedFort visit is started
 visitng RedFort....


JamaMasjid accept the visotr and welcomes him

JamaMasjid visit is started
 visitng JamaMasjid....


Visotor Thanks  all .. It wwas wondeful experience... truly incredible India