Monday, October 21, 2024

Command Design Pattern using lambda expression

 Command design pattern: The main concept of command pattern is how the command will be executed that process is encapsulated in a class . So the the process will be hide into that class.

Command :  Command object knows about receiver and call a method of receiver.

Receiver:  Who receives command and acts based on that command;

Invoker: Who only have reference of command interface . Who does not know about the implementation of the command . 

Client: It hold all the list of command. Just invoke to the invoker whatever need .

Example:

Command:

public interface Command {
    void execute();
}

public class OnCommand implements Command {
    private Tv tv;
    public OnCommand(Tv tv) {
        this.tv = tv;
    }
    @Override
    public void execute() {
        tv.switchOn();
    }
}

 public class OffCommand implements Command {
    private Tv tv;
    public OffCommand(Tv tv) {
        this.tv = tv;
    }
    @Override
    public void execute() {
        tv.switchOff();
    }
}

Invoker:

public class RemoteControl {
    private List<Command> history = new ArrayList<>();
    public void press(Command command) {
        history.add(command);
        command.execute();
    }
}

Client:

public class TvClient {
    public static void main(String[] args) {
        Tv tv = new Tv();

        Command onCommand = new OnCommand(tv);

        Command offCommand = new OffCommand(tv);
        RemoteControl remote = new RemoteControl();
        remote.press(onCommand);
        remote.press(offCommand);
    }
}

Here command interface has  one abstract method. So we can use lambda expression here . so no need to create OnCommand and OffCommand class .

public class TvClient {
    public static void main(String[] args) {
        Tv tv = new Tv();
        RemoteControl remote = new RemoteControl();
        remote.press(tv - > switchOn);
        remote.press(tv -> switchOff);

    }

we can replace it using method reference also ,

public class TvClient {
    public static void main(String[] args) {
        Tv tv = new Tv();
        RemoteControl remote = new RemoteControl();
        remote.press(tv:: switchOn);
        remote.press(tv:: switchOff);

    }
}

No comments:

Post a Comment

Fluent interface pattern

 public class UserConfigurationManager {     private String userName;     private String password;     private UserConfigurationManager() { ...