Thursday, 17 October 2013

Prototype Design pattern - Implementation


Click here to watch in Youtube : https://www.youtube.com/watch?v=nZqoK4uaoZc

Click the below Image to Enlarge
Prototype Design pattern - Implementation
Prototype Design pattern - Implementation - Class Diagram









































Dogear.java

public class Dogear
{
private int numberOfEars;

public int getNumberOfEars()
{
return numberOfEars;
}

public void setNumberOfEars( int numberOfEars )
{
this.numberOfEars = numberOfEars;
}

@Override
        public String toString()
        {
       return "Dogear [numberOfEars=" + numberOfEars + "]";
        }


}

Dogeye.java

public class Dogeye
{
private int numberOfEyes;

public int getNumberOfEyes()
{
return numberOfEyes;
}

public void setNumberOfEyes( int numberOfEyes )
{
this.numberOfEyes = numberOfEyes;
}

@Override
        public String toString()
        {
       return "Dogeye [numberOfEyes=" + numberOfEyes + "]";
        }


}


Dogleg.java

public class Dogleg
{
private int numberOflegs;

public int getNumberOflegs()
{
return numberOflegs;
}

public void setNumberOflegs( int numberOflegs )
{
this.numberOflegs = numberOflegs;
}

@Override
        public String toString()
        {
       return "Dogleg [numberOflegs=" + numberOflegs + "]";
        }


}


Dogtail.java

public class Dogtail
{
private String tailLength; // long or small

public String getTailLength()
{
return tailLength;
}

public void setTailLength( String tailLength )
{
this.tailLength = tailLength;
}

@Override
        public String toString()
        {
       return "Dogtail [tailLength=" + tailLength + "]";
        }

}


Animal.java

public interface Animal extends Cloneable
{
 public Animal clone();

}


Dog.java

public class Dog implements Animal
{

private String  name;
private int     age;
private String  color;
private Dogleg  dogleg;
private Dogtail dogtail;
private Dogear  dogear;
private Dogeye  dogeye;

public Dog( String name, int age, String color, Dogleg dogleg, Dogtail dogtail, Dogear dogear, Dogeye dogeye )
{
super();
this.name = name;
this.age = age;
this.color = color;
this.dogleg = dogleg;
this.dogtail = dogtail;
this.dogear = dogear;
this.dogeye = dogeye;
}

public Dogleg getDogleg()
{
return dogleg;
}

public void setDogleg( Dogleg dogleg )
{
this.dogleg = dogleg;
}

public Dogtail getDogtail()
{
return dogtail;
}

public void setDogtail( Dogtail dogtail )
{
this.dogtail = dogtail;
}

public Dogear getDogear()
{
return dogear;
}

public void setDogear( Dogear dogear )
{
this.dogear = dogear;
}

public Dogeye getDogeye()
{
return dogeye;
}

public void setDogeye( Dogeye dogeye )
{
this.dogeye = dogeye;
}

public String getName()
{
return name;
}

public void setName( String name )
{
this.name = name;
}

public int getAge()
{
return age;
}

public void setAge( int age )
{
this.age = age;
}

public String getColor()
{
return color;
}

public void setColor( String color )
{
this.color = color;
}

public Animal clone()
{

Dog dogObject = null;

try
{

dogObject = (Dog) super.clone();

}

catch( CloneNotSupportedException e )
{

e.printStackTrace();

}

return dogObject;
}

@Override
public String toString()
{
return "Dog [name=" + name + ", age=" + age + ", color=" + color + ", dogleg=" + dogleg + ", dogtail="
               + dogtail + ", dogear=" + dogear + ", dogeye=" + dogeye + "]";
}

}


AnimalCache.java

import java.util.Hashtable;

public class AnimalCache
{
private static Hashtable<String, Animal> AnimalMap = new Hashtable<String, Animal>();

public static Animal getAnimal( String animalType )
{
Dog dog = (Dog) AnimalMap.get(animalType);
if( dog == null )
{
Dogleg dogleg = new Dogleg();
dogleg.setNumberOflegs(4);

Dogear dogear = new Dogear();
dogear.setNumberOfEars(2);

Dogtail dogtail = new Dogtail();
dogtail.setTailLength("long");

Dogeye dogeye = new Dogeye();
dogeye.setNumberOfEyes(2);

dog = new Dog("Tommy", 3, "White", dogleg, dogtail, dogear, dogeye);
AnimalMap.put("dog", dog);
System.out.println("New Dog Object is created and return\n");
return dog;
}
System.out.println("\nCloned Dog Object is created and return\n");
return dog.clone();
}
}


PrototypePatternDemo.java

public class PrototypePatternDemo
{

public static void main(String[] args)
{

Dog dog = (Dog) AnimalCache.getAnimal("dog");
displayAnimalProperty(dog);

Dog cloneddog1 = (Dog) AnimalCache.getAnimal("dog");
cloneddog1.setName("Jonnie");
cloneddog1.setAge(4);
cloneddog1.setColor("Brown");
displayAnimalProperty(cloneddog1);

Dog cloneddog2 = (Dog) AnimalCache.getAnimal("dog");
cloneddog2.setName("Tony");
cloneddog2.setAge(5);
cloneddog2.setColor("Brown");
displayAnimalProperty(cloneddog2);

Dog cloneddog3 = (Dog) AnimalCache.getAnimal("dog");
cloneddog3.setName("Jimmy");
cloneddog3.setAge(8);
cloneddog3.setColor("Brown");
displayAnimalProperty(cloneddog3);

}

public static void displayAnimalProperty(Animal animal)
{
if (animal instanceof Dog)
{
Dog dog = (Dog) animal;
System.out.println(dog.toString());
System.out.println("-----------------------------------------------------------------------------------------------------");

}
}

}

Output

New Dog Object is created and return

Dog [name=Tommy, age=3, color=White, dogleg=Dogleg [numberOflegs=4], dogtail=Dogtail [tailLength=long], dogear=Dogear [numberOfEars=2], dogeye=Dogeye [numberOfEyes=2]]
-----------------------------------------------------------------------------------------------------

Cloned Dog Object is created and return

Dog [name=Jonnie, age=4, color=Brown, dogleg=Dogleg [numberOflegs=4], dogtail=Dogtail [tailLength=long], dogear=Dogear [numberOfEars=2], dogeye=Dogeye [numberOfEyes=2]]
-----------------------------------------------------------------------------------------------------

Cloned Dog Object is created and return

Dog [name=Tony, age=5, color=Brown, dogleg=Dogleg [numberOflegs=4], dogtail=Dogtail [tailLength=long], dogear=Dogear [numberOfEars=2], dogeye=Dogeye [numberOfEyes=2]]
-----------------------------------------------------------------------------------------------------

Cloned Dog Object is created and return

Dog [name=Jimmy, age=8, color=Brown, dogleg=Dogleg [numberOflegs=4], dogtail=Dogtail [tailLength=long], dogear=Dogear [numberOfEars=2], dogeye=Dogeye [numberOfEyes=2]]
-----------------------------------------------------------------------------------------------------


See also:


  • Prototype Design Pattern - Introduction
  • Prototype Design Pattern - Class Diagram
  • Prototype Design Pattern - KeyPoints
  • All Design Patterns Links
  • Tuesday, 15 October 2013

    Chain of Responsibility Design pattern - Implementation(One or more Rece...



    Click here to watch in Youtube : https://www.youtube.com/watch?v=tyGnCb-kE1I

    Click the below Image to Enlarge
    Chain of Responsibility Design pattern - Implementation
    Chain of Responsibility Design pattern - Implementation - Class Diagram




































    RsHandler.java

    public abstract class RsHandler
    {
    RsHandler rsHandler;

    public void nextHandler( RsHandler rsHandler )
    {
    this.rsHandler = rsHandler;
    }

    public abstract void dispatchRs( long requestedAmount );

    }

    HundredRsHandler.java

    public class HundredRsHandler extends RsHandler
    {

    public void dispatchRs(long requestedAmount)
    {
    long numberofNotesToBeDispatched = requestedAmount / 100;
    if (numberofNotesToBeDispatched > 0)
    {
    if(numberofNotesToBeDispatched>1)
    {
    System.out.println(numberofNotesToBeDispatched + " ,Hundred Rs notes are dispatched by HundredRsHandler\n");
    }
    else
    {
    System.out.println(numberofNotesToBeDispatched + " ,Hundred Rs note is dispatched by HundredRsHandler\n");

    }
    }

    long pendingAmountToBeProcessed = requestedAmount % 100;

    if (pendingAmountToBeProcessed > 0)
    {
    rsHandler.dispatchRs(pendingAmountToBeProcessed);

    }

    }

    }

    FiftyRsHandler.java

    public class FiftyRsHandler extends RsHandler
    {
    public void dispatchRs(long requestedAmount)
    {
    long numberofNotesToBeDispatched = requestedAmount / 50;
    if (numberofNotesToBeDispatched > 0)
    {
    if (numberofNotesToBeDispatched > 1)
    {
    System.out.println(numberofNotesToBeDispatched + " ,Fifty Rs notes are dispatched by FiftyRsHandler\n");
    }
    else
    {
    System.out.println(numberofNotesToBeDispatched + " ,Fifty Rs note is dispatched by FiftyRsHandler\n");

    }

    }

    long pendingAmountToBeProcessed = requestedAmount % 50;

    if (pendingAmountToBeProcessed > 0)
    {
    rsHandler.dispatchRs(pendingAmountToBeProcessed);

    }

    }
    }


    TwentyRsHandler.java

    public class TwentyRsHandler extends RsHandler
    {
    public void dispatchRs(long requestedAmount)
    {
    long numberofNotesToBeDispatched = requestedAmount / 20;

    if (numberofNotesToBeDispatched > 0)
    {

    if (numberofNotesToBeDispatched > 1)
    {
    System.out.println(numberofNotesToBeDispatched + " ,Twenty Rs notes are dispatched by TwentyRsHandler\n");
    }
    else
    {
    System.out.println(numberofNotesToBeDispatched + " ,Twenty Rs note is dispatched by TwentyRsHandler\n");

    }
    }

    long pendingAmountToBeProcessed = requestedAmount % 20;

    if (pendingAmountToBeProcessed > 0)
    {
    rsHandler.dispatchRs(pendingAmountToBeProcessed);

    }

    }
    }


    FiveRsHandler.java

    public class FiveRsHandler extends RsHandler
    {
    public void dispatchRs(long requestedAmount)
    {
    long numberofNotesToBeDispatched = requestedAmount / 5;
    if (numberofNotesToBeDispatched > 0)
    {

    if (numberofNotesToBeDispatched > 1)
    {
    System.out.println(numberofNotesToBeDispatched + " ,Five Rs notes are dispatched by FiveRsHandler\n");
    }
    else
    {
    System.out.println(numberofNotesToBeDispatched + " ,Five Rs note is dispatched by FiveRsHandler\n");

    }
    }

    long pendingAmountToBeProcessed = requestedAmount % 5;

    if (pendingAmountToBeProcessed > 0)
    {
    rsHandler.dispatchRs(pendingAmountToBeProcessed);

    }

    }
    }


    ATM.java

    public class ATM
    {
    private static HundredRsHandler hundredRsHandler = new HundredRsHandler();
    private static FiftyRsHandler   fiftyRsHandler   = new FiftyRsHandler();
    private static TwentyRsHandler  twentyRsHandler  = new TwentyRsHandler();
    private static FiveRsHandler    fiveRsHandler    = new FiveRsHandler();

    static
    {
    // Prepare the chain of Handlers
    hundredRsHandler.nextHandler(fiftyRsHandler);
    fiftyRsHandler.nextHandler(twentyRsHandler);
    twentyRsHandler.nextHandler(fiveRsHandler);
    }

    public void withdraw( long requestedAmount )
    {

    hundredRsHandler.dispatchRs(requestedAmount);
    }
    }


    ChainOfResDemo.java

    public class ChainOfResDemo
    {

    public static void main( String[] args )
    {
    ATM atm = new ATM();
    System.out.println("\n ----------------Requested Amount 475-----------------------\n");
    atm.withdraw(475);
    System.out.println("\n ----------------Requested Amount 455-----------------------\n");
    atm.withdraw(455);
    System.out.println("\n ----------------Requested Amount 520-----------------------\n");
    atm.withdraw(520);
    }

    }


    Output

     ----------------Requested Amount 475-----------------------

    4 ,Hundred Rs notes are dispatched by HundredRsHandler

    1 ,Fifty Rs note is dispatched by FiftyRsHandler

    1 ,Twenty Rs note is dispatched by TwentyRsHandler

    1 ,Five Rs note is dispatched by FiveRsHandler


     ----------------Requested Amount 455-----------------------

    4 ,Hundred Rs notes are dispatched by HundredRsHandler

    1 ,Fifty Rs note is dispatched by FiftyRsHandler

    1 ,Five Rs note is dispatched by FiveRsHandler


     ----------------Requested Amount 520-----------------------

    5 ,Hundred Rs notes are dispatched by HundredRsHandler

    1 ,Twenty Rs note is dispatched by TwentyRsHandler



    Saturday, 12 October 2013

    Chain Of Responsibility Design Pattern - Implementation


    Click here to watch in Youtube : https://www.youtube.com/watch?v=EiU5mIHknGo

    Click the below Image to Enlarge
    Chain Of Responsibility Design Pattern - Implementation

    Chain Of Responsibility Design Pattern - Implementation - Class Diagram


































    Employee.java

    public abstract class Employee
    {

    // next element in chain or responsibility
    protected Employee supervisor;

    public void setNextSupervisor( Employee supervisor )
    {
    this.supervisor = supervisor;
    }

    public abstract void applyLeave( String employeeName, int numberofDaysLeave );
    }


    TeamLeader.java

    public class TeamLeader extends Employee
    {
    // TeamLeader can only approve upto 10 days of leave
    private int MAX_LEAVES_CAN_APPROVE = 10;

    public void applyLeave( String employeeName, int numberofDaysLeave )
    {
     // check if TeamLeader can process this request
    if( numberofDaysLeave <= MAX_LEAVES_CAN_APPROVE )
    {
    ApproveLeave(employeeName, numberofDaysLeave);
    }
     // if TeamLeader can't process the LeaveRequest then pass on to the supervisor(ProjectLeader)
                 // so that he can process
    else
    {
    supervisor.applyLeave(employeeName, numberofDaysLeave);
    }
    }

    private void ApproveLeave( String employeeName, int numberofDaysLeave )
    {
    System.out.println("TeamLeader approved " + numberofDaysLeave + " days " + "Leave for the employee : "
                    + employeeName);

    }
    }

    ProjectLeader.java

    public class ProjectLeader extends Employee
    {
    // ProjectLeader can only approve upto 20 days of leave
    private int MAX_LEAVES_CAN_APPROVE = 20;

    public void applyLeave( String employeeName, int numberofDaysLeave )
    {
     // check if ProjectLeader can process this request
    if( numberofDaysLeave <= MAX_LEAVES_CAN_APPROVE )
    {
    ApproveLeave(employeeName, numberofDaysLeave);
    }
    // if ProjectLeader can't process the LeaveRequest then pass on to the supervisor(HR) 
                 // so that he can process
    else
    {
    supervisor.applyLeave(employeeName, numberofDaysLeave);
    }
    }

    private void ApproveLeave( String employeeName, int numberofDaysLeave )
    {
    System.out.println("ProjectLeader approved " + numberofDaysLeave + " days " + "Leave for the employee : "
                    + employeeName);

    }
    }


    HR.java

    public class HR extends Employee
    {
    // HR can only approve upto 30 days of leave
    private int MAX_LEAVES_CAN_APPROVE = 30;

    public void applyLeave( String employeeName, int numberofDaysLeave )
    {
    if( numberofDaysLeave <= MAX_LEAVES_CAN_APPROVE )
    {
    ApproveLeave(employeeName, numberofDaysLeave);
    }
    else
    {
    System.out.println("Leave application suspended, Please contact HR");
    }
    }

    private void ApproveLeave( String employeeName, int numberofDaysLeave )
    {
    System.out.println("HR approved " + numberofDaysLeave + " days " + "Leave for the employee : "
                    + employeeName);

    }
    }


    ChainPatternDemo.java

    public class ChainPatternDemo
    {

    public static void main( String[] args )
    {
    TeamLeader teamLeader= new TeamLeader();
    ProjectLeader projectLeader= new ProjectLeader();
    HR hr=new HR();
    teamLeader.setNextSupervisor(projectLeader);
    projectLeader.setNextSupervisor(hr);
    teamLeader.applyLeave("David", 9);
    System.out.println();
    teamLeader.applyLeave("John", 18);
    System.out.println();
    teamLeader.applyLeave("Steve", 30);
    System.out.println();
    teamLeader.applyLeave("Rohan", 50);

    }

    }


    Output

    TeamLeader approved 9 days Leave for the employee : David

    ProjectLeader approved 18 days Leave for the employee : John

    HR approved 30 days Leave for the employee : Steve

    Leave application suspended, Please contact HR


    See also:

  • Chain of Responsibility Design Pattern - Introduction
  • Chain of Responsibility Design Pattern - Real time Example
  • Chain of Responsibility Design Pattern - Class and Sequence Diagram
  • Chain of Responsibility Design Pattern - Implementation(one or more Receiver)
  • Chain of Responsibility Design Pattern - Key Points
  • All Design Patterns Links
  • Composite Design Pattern - Implementation



    Click here to watch in Youtube : https://www.youtube.com/watch?v=HM1Zn-uVF60

    Click the below Image to Enlarge

    Composite Design Pattern - Implementation

    Composite Design Pattern - Implementation - Class Diagram

























    IEmployee.java

    public interface IEmployee
    {
    public int getYearlySalary();

    }

    Employee.java

    import java.util.ArrayList;

    // Employee class is the Composite node [i.e. it can have other objects below it]

    public class Employee implements IEmployee
    {

    private String               name;
    private int                  monthlySalary;
    // Employee designation Can be CEO,Dev Manager,QA Manager,Dev TeamLead,QA TeamLead
    private String               designation;

    private ArrayList<IEmployee> subordinateList = new ArrayList<IEmployee>();

    public Employee( String name, int monthlySalary, String designation )
    {
    super();
    this.name = name;
    this.monthlySalary = monthlySalary;
    this.designation = designation;
    }

    public String getName()
    {
    return name;
    }

    public void setName( String name )
    {
    this.name = name;
    }

    public int getMonthlySalary()
    {
    return monthlySalary;
    }

    public void setMonthlySalary( int monthlySalary )
    {
    this.monthlySalary = monthlySalary;
    }

    public String getDesignation()
    {
    return designation;
    }

    public void setDesignation( String designation )
    {
    this.designation = designation;
    }

    public ArrayList<IEmployee> getSubordinateList()
    {
    return subordinateList;
    }

    public void setSubordinateList( ArrayList<IEmployee> subordinateList )
    {
    this.subordinateList = subordinateList;
    }

    @Override
    public int getYearlySalary()
    {
    return monthlySalary * 12;
    }

    public void addSubordinate( IEmployee employee )
    {
    subordinateList.add(employee);
    }

    public void removeSubordinate( IEmployee employee )
    {
    subordinateList.remove(employee);
    }

    public ArrayList<IEmployee> getChilds()
    {
    return getSubordinateList();
    }

    }


    SoftwareEngineer.java

    // SoftwareEngineer class is the Leaf node [i.e. it cann't have other objects below it]

    public class SoftwareEngineer implements IEmployee
    {
    private String name;
    private int    monthlySalary;
    // Employee designation Can be Dev Software Engineer, QA Software Engineer
    private String designation;

    public SoftwareEngineer( String name, int monthlySalary, String designation )
    {
    super();
    this.name = name;
    this.monthlySalary = monthlySalary;
    this.designation = designation;
    }

    public String getName()
    {
    return name;
    }

    public void setName( String name )
    {
    this.name = name;
    }

    public int getMonthlySalary()
    {
    return monthlySalary;
    }

    public void setMonthlySalary( int monthlySalary )
    {
    this.monthlySalary = monthlySalary;
    }

    public String getDesignation()
    {
    return designation;
    }

    public void setDesignation( String designation )
    {
    this.designation = designation;
    }

    @Override
    public int getYearlySalary()
    {
    return monthlySalary * 12;
    }

    }


    CompositePatternDemo.java

    import java.util.ArrayList;

    public class CompositePatternDemo
    {

    public static void main( String[] args )
    {
    Employee dave = new Employee("Dave", 200000, "CEO");

    Employee peter = new Employee("peter", 100000, "Dev Manager");
    Employee john = new Employee("John", 100000, "QA Manager");

    Employee rohan = new Employee("Rohan", 50000, "Dev TeamLead");
    Employee vijay = new Employee("Vijay", 50000, "QA TeamLead");

    SoftwareEngineer raj = new SoftwareEngineer("Raj", 30000, "Dev Software Engineer");
    SoftwareEngineer mohan = new SoftwareEngineer("Mohan", 30000, "Dev Software Engineer");
    SoftwareEngineer hema = new SoftwareEngineer("Hema", 30000, "Dev Software Engineer");

    SoftwareEngineer saran = new SoftwareEngineer("Saran", 20000, "QA Software Engineer");
    SoftwareEngineer riya = new SoftwareEngineer("Riya", 20000, "QA Software Engineer");

    dave.addSubordinate(peter);
    dave.addSubordinate(john);

    peter.addSubordinate(rohan);
    john.addSubordinate(vijay);

    rohan.addSubordinate(raj);
    rohan.addSubordinate(mohan);
    rohan.addSubordinate(hema);

    vijay.addSubordinate(saran);
    vijay.addSubordinate(riya);


    getSubOrdinates(dave);
    getSubOrdinates(peter);
    getSubOrdinates(john);
    getSubOrdinates(rohan);
    getSubOrdinates(vijay);
    getSubOrdinates(raj);
    getSubOrdinates(mohan);
    getSubOrdinates(hema);
    getSubOrdinates(saran);
    getSubOrdinates(riya);
    }

    private static void getSubOrdinates( IEmployee iemployee )
    {
    if( iemployee instanceof Employee )
    {
    Employee employee = (Employee) iemployee;
    System.out.println("\n------------- SubordinatesListOf "+ employee.getName() +" : "+employee.getDesignation() + " ---------------------------------\n");
    ArrayList<IEmployee> subordinatesListOfDave = employee.getChilds();
    for( IEmployee iEmployee : subordinatesListOfDave )
    {
    if( iEmployee instanceof Employee )
    {
    Employee employeeObj = (Employee) iEmployee;
    System.out.println(employeeObj.getName() + " : " + employeeObj.getDesignation() + ":"
                   + employeeObj.getMonthlySalary() + ":" + employeeObj.getYearlySalary());
    }
    else
    {
    SoftwareEngineer softwareEngineer = (SoftwareEngineer) iEmployee;
    System.out.println(softwareEngineer.getName() + " : "
                   + softwareEngineer.getDesignation() + ":"
                   + softwareEngineer.getMonthlySalary() + ":"
                   + softwareEngineer.getYearlySalary());

    }

    }
    }
    else
    {
    System.out.println("\n--------------------------------------------------------------------------------------");
    SoftwareEngineer softwareEngineer = (SoftwareEngineer) iemployee;
    System.out.println("\nNo Subordinates for "+softwareEngineer.getName()+" : "+softwareEngineer.getDesignation()
    +" : "+softwareEngineer.getMonthlySalary()+" : "+softwareEngineer.getYearlySalary());
    }
    }

    }


    Output

    ------------- SubordinatesListOf Dave : CEO ---------------------------------

    peter : Dev Manager:100000:1200000
    John : QA Manager:100000:1200000

    ------------- SubordinatesListOf peter : Dev Manager ---------------------------------

    Rohan : Dev TeamLead:50000:600000

    ------------- SubordinatesListOf John : QA Manager ---------------------------------

    Vijay : QA TeamLead:50000:600000

    ------------- SubordinatesListOf Rohan : Dev TeamLead ---------------------------------

    Raj : Dev Software Engineer:30000:360000
    Mohan : Dev Software Engineer:30000:360000
    Hema : Dev Software Engineer:30000:360000

    ------------- SubordinatesListOf Vijay : QA TeamLead ---------------------------------

    Saran : QA Software Engineer:20000:240000
    Riya : QA Software Engineer:20000:240000

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

    No Subordinates for Raj : Dev Software Engineer : 30000 : 360000

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

    No Subordinates for Mohan : Dev Software Engineer : 30000 : 360000

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

    No Subordinates for Hema : Dev Software Engineer : 30000 : 360000

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

    No Subordinates for Saran : QA Software Engineer : 20000 : 240000

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

    No Subordinates for Riya : QA Software Engineer : 20000 : 240000