Design Patterns Java - Command Php

1) What have we done?

We just created interface "Command" which deine method "execute"


public interface Command
{
    void execute();
}




We would like to calling "doA" and "doB" log so just created abstract class "LoggerCommand" where we inject "Receiver" and "Logger"


public abstract class LoggerCommand implements Command
{
    protected Logger logger;

    protected Receiver receiver;

    public LoggerCommand(Receiver receiver, Logger logger)
    {
        this.logger = logger;
        this.receiver = receiver;
    }
}




And two concrete classes "LoggerCommandA" and "LoggerCommandB" for log methods respectively "doA" and "doB"


public class LoggerCommandA extends LoggerCommand
{
    public LoggerCommandA(Receiver receiver, Logger logger)
    {
        super(receiver, logger);
    }

    @Override
    public void execute()
    {
        receiver.doA();
        logger.log("Class Receiver executed method doA");
    }
}

public class LoggerCommandB extends LoggerCommand
{
    public LoggerCommandB(Receiver receiver, Logger logger)
    {
        super(receiver, logger);
    }

    @Override
    public void execute()
    {
        receiver.doB();
        logger.log("Class Receiver executed method doB");
    }
}




2) What really we did?

Instead of direct calling "doA" and "doB" we just call method "execute" on "Command" objects, which by the way of calling proper method also log calling of these methods.


public class Client
{
    public static void main(String[] args)
    {
        Receiver receiver = new Receiver();
        Logger logger = new Logger();

        Command commandA = new LoggerCommandA(receiver, logger);
        Command commandB = new LoggerCommandB(receiver, logger);

        commandA.execute();
        commandB.execute();
    }
}




Now thanks for this pattern we have many pros
- we can create method(like "Command" object" - and later execute it
- we can add there own stuffs - logging, history, undoing
- "Receiver" has stayed untouched