Showing posts with label Command design pattern. Show all posts
Showing posts with label Command design pattern. Show all posts

Monday, December 2

Command Design Pattern

Consider yourself a referee of a race where you need to give below commands to athletes

Ready -- Athlete to get ready for race
Set  ---
Athletes to all set to run
Go  ---
Athletes to run the race

How can we automate this in java using command design pattern .





Lets consider there is a Race class which defines there action


public class Race {

    public void getReady() {

        System.out.println("getting ready");
    }

    public void set() {
        System.out.println("setting running position");

    }

    public void go() {
        System.out.println("running");

    }
}



Now we need to create there command classes for these three actions

Let's create an interface first which basically will be uniformly implemented by all there command classes

Interface name is Position. It is declaring single method execute()


public interface Position {

    public void execute();
}







Next there command classes

Ready , Set and Go


public class Ready implements Position {

    Race race;   
    public Ready(Race race){
        this.race=race;
    }
    @Override
    public void execute() {

        race.getReady();

    }
}



public class Set implements Position {

    Race race;   
    public Set(Race race){
        this.race=race;
    }
   
    @Override
    public void execute() {
        race.set();
    }

}


public class Go implements Position {

    Race race;   
    public Go(Race race){
        this.race=race;
    }
   
    @Override
    public void execute() {
        race.go();

    }

}



-->


Every command class has one argument constructor which allows Command instances set Race class instance to execute the method on Race class.

Now it is duty of Referee to pass instance of Race class to Commands and Commands will execute() the method invoked inside execute() method.

Here is Referee class


public class Referee {

    public static void main(String args[]){
        Race race=new Race();
       
        Position position1=new Ready(race);
        Position position2=new Set(race);
        Position position3=new Go(race);
       
        position1.execute();
        position2.execute();
        position3.execute();

       
        }

}


Put together all these classes and execute program as java application. That will print below logs on console :



getting ready
setting running position
running