Saturday 1 October 2022

 Design Pattern: Command

a)Command Design Pattern:

In command design pattern, we overwrite a method in interface in such a way that we can automate operations like LIGHTS ON or OFF, BUTTON ON or OFF, MODE ON or OFF, MACHINE ON or OFF, etc.

Basically, this design pattern is used to execute binary (ON or OFF), ternary (ON, HOLD, OFF) or multiple stages of operation (like MODE 1, 2, 3 , 4, 5, 6, etc in various machines)

//create an interface with execute method defined in it

a) interface Command{

    public void execute();

}

// create a concrete class which will have different operations in it

b) public class Bulb {

   public void on(){

       System.out.println("Bulb is turned on");

}

  public void off(){

     System.out.println("Bulb is turned off");

}

}

//Create a concrete class which will execute command design pattern

c) public class BulbOnCommand implements Command {

     private Bulb bulb;

     public BulbOnCommand(Bulb bulb){

     this.bulb = bulb;

}

  public void execute(){

 bulb.on();  }

}

d) public class BulbOffCommand implements Command {

     private Bulb bulb;

     public BulbOffCommand(Bulb bulb){

     this.bulb = bulb;

}

  public void execute(){

 bulb.off();  }

}

//User class which will execute command logic

e) public class CommandDemo {

    Command command = new 



}

No comments:

Post a Comment