Showing posts with label command pattern. Show all posts
Showing posts with label command pattern. Show all posts

Friday, August 8, 2014

Programming Design Pattern - Command Pattern Applied - Best Practise

Hi there!

Today i'm gonna share with you a really great programming design pattern. It has a lot of usages and it is one of my favorites. The programming degin pattern command has a huge variety of use cases. In this post we will see how to implement something from the real world.

We will implement an electronic car key to open, close doors, enable, disable alarms, open, close the garage door or to open and close the hood and trunk of your car.

The example i will show to you, is a very generic one, so you can always come back here, take it and use it in your applications.

The UML Command Pattern

As you know me, i always start my projects by showing the class diagram over a UML diagram. This help us to fix it overview the example in a nice, compact way.


Explaning the Details Programming Design

Our client is the Ferrari Owner (FerrariCleint). It has a CarKey. The CarKey has a generic MicroShip (Involker) that can be configurated with commands. The commands (OpenDoorCommand) itself have Action (DoorAction) to execute. The CarKey can configurate do and undo Commands. The NullObjectCommand belongs to the Null Object Design Pattern and it will be also used here. Let's see in the code the implementation details now.

Command and MicroShip

The NullObjectCommand is used here to avoid null pointer exceptions and to execute nothing as long as no command has been defined.

public interface Command {
    void execute();
}
public class MicroChip {
    protected Command[] onCommands;
    protected Command[] offCommands;
    public MicroChip(int commandQuantity) {
        onCommands =  new Command[commandQuantity];
        offCommands = new Command[commandQuantity];
        Command nullObjecCommand =  new NullObjectCommand();
        for (int i = 0; i < commandQuantity; i++) {
            onCommands[i]=nullObjecCommand;
            offCommands[i]=nullObjecCommand;
        }
    }
    public void configureCommand(int position, Command on, Command off){
        onCommands[position]=on;
        offCommands[position]=off;
    }
    public void executeOnCommand(int position){
        onCommands[position].execute();
    }
    public void executeOffCommand(int position){
        offCommands[position].execute();
    }
    protected class NullObjectCommand implements Command{
        @Override
        public void execute() {
            // NULL-OBJECT-PATTERN
        }
    }
}

Concrete Commands and Actions

Here we can see the concrete implementation of Actions and Commands.
public class Door {
    public void on(){
        System.out.println("Opening car doors...");
    }
    public void off(){
        System.out.println("Closing car doors...");
    }
}
public class OpenDoorCommand implements Command {

    private Door door;
    public OpenDoorCommand(Door door) {
        this.door = door;
    }
    @Override
    public void execute() {
        door.on();
    }
}
public class CloseDoorCommand implements Command {

    private Door door;
    public CloseDoorCommand(Door door) {
        this.door =door;
    }
    @Override
    public void execute() {
        door.off();
    }
}

The Generic MicroShip

As you can see here, this implementation or this MicroShip can hold as many commands as you need and can be reused in any situation you may need. In this MicroShip bellow i have implemented more then only this OpenDoorCommand and CloseDoorCommand above, so you can see the power of it. It is up to you to implement other commands like i did.The cool thing here is the ability to do and undo things. To create as many commands and exucute as many actions as we need. The simplicity and beauty of this pattern fascinates me.

public class CarKey {
    private MicroChip microChip;
    public CarKey() {
        final int commandQuantity = 5;
        microChip = new MicroChip(commandQuantity);
        
        final Hood hood = new Hood();
        final OpenHoodCommand openHoodCmd = new OpenHoodCommand(hood);
        final CloseHoodCommand closeHoodCmd = new CloseHoodCommand(hood);
        microChip.configureCommand(0, openHoodCmd, closeHoodCmd);
        
        final Door door = new Door();
        final OpenDoorCommand openDoorCmd = new OpenDoorCommand(door);
        final CloseDoorCommand closeDoorCmd = new CloseDoorCommand(door);
        microChip.configureCommand(1, openDoorCmd, closeDoorCmd);
        
        final Garage garage = new Garage();
        final OpenGarageCommand openGarageCmd = new OpenGarageCommand(garage);
        final CloseGarageCommand closeGarageCmd = new CloseGarageCommand(garage);
        microChip.configureCommand(2, openGarageCmd, closeGarageCmd);
        
        final Trunk trunk = new Trunk();
        final OpenTrunkCommand openTrunkCmd = new OpenTrunkCommand(trunk);
        final CloseTrunkCommand closeTrunkCmd = new CloseTrunkCommand(trunk);
        microChip.configureCommand(3, openTrunkCmd, closeTrunkCmd);
        
        final Alarm alarm = new Alarm();
        final EnableAlarmCommand enableAlarmCmd = new EnableAlarmCommand(alarm);
        final DisableAlarmCommand disableAlarmCmd = new DisableAlarmCommand(alarm);
        microChip.configureCommand(4, enableAlarmCmd, disableAlarmCmd);
    }
    
    public void openHood(){microChip.executeOnCommand(0);}
    public void closeHood(){microChip.executeOffCommand(0);}
    public void openDoor(){microChip.executeOnCommand(1);}
    public void closeDoor(){microChip.executeOffCommand(1);}
    public void openGarage(){microChip.executeOnCommand(2);}
    public void closeGarage(){microChip.executeOffCommand(2);}
    public void openTrunk(){microChip.executeOnCommand(3);}
    public void closeTrunk(){microChip.executeOffCommand(3);}
    public void enableAlarm(){microChip.executeOnCommand(4);}
    public void disableAlarm(){microChip.executeOffCommand(4);}

}

The FerrariClient

Finally we can see the usage and power of this beautiful design pattern. In this example i implemented more than one command to show to you, how it could looks like.

public class FerrariClient {
    public static void main(String[] args) {
        final CarKey ferrariSwitchbladeKey = new CarKey();
        ferrariSwitchbladeKey.openHood();
        ferrariSwitchbladeKey.openGarage();
        ferrariSwitchbladeKey.openTrunk();
        ferrariSwitchbladeKey.openDoor();
        ferrariSwitchbladeKey.enableAlarm();
        System.out.println("-------------------------------");
        ferrariSwitchbladeKey.closeHood();
        ferrariSwitchbladeKey.closeGarage();
        ferrariSwitchbladeKey.closeTrunk();
        ferrariSwitchbladeKey.closeDoor();
        ferrariSwitchbladeKey.disableAlarm();
    }
}

That's all. Hope you like it!

😱👇 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘‡

Be sure to read, it will change your life!
Show your work by Austin Kleonhttps://amzn.to/34NVmwx

This book is a must read - it will put you in another level! (Expert)
Agile Software Development, Principles, Patterns, and Practiceshttps://amzn.to/30WQSm2

Write cleaner code and stand out!
Clean Code - A Handbook of Agile Software Craftsmanship: https://amzn.to/33RvaSv

This book is very practical, straightforward and to the point! Worth every penny!
Kotlin for Android App Development (Developer's Library): https://amzn.to/33VZ6gp

Needless to say, these are top right?

😱👆 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘†

Saturday, December 7, 2013

How to identify design pattern before coding?

Hi there!

In this post we will learn how to identify design pattern before coding! Isn't it exciting? As you probabilly know, i'm addicted to design patterns. I've read a lot of good books and probabilly as you, my biggest problem was always the identification of cases/scenarios in which i could use them.

There are great books out there, but none of them explains in a simple way, how to identify it. Most of them says: "It depends on the usecase or it depends on the dev's expirience" In fact the expirience (years that you have been working on the software business) may help you identifying the right patterns to be used in some default scenarios, but can't we learn it a little bit faster? Do we have to wait years to get it done right?

Motivated by those questions, i've been trying to identify the patterns by the last mobile project i made. I was very surprised how simple it can be and how much better understandable, extensible and readable my end project was. All you need to do is to sketch it first. Really!!! That's all. Don't worry, we will see the whole process step by step. :-)

The Patterns

In this tutorial we will learn how i was able to identify a bunch of patterns before starting coding (Please note: In this tutorial i will not explain why a specific pattern is good or not. I will assume you know already design pattern and are interested in see how/when to apply it) In my project i was able to identify the following patterns:

  • Command Pattern
  • State Pattern
  • Adapter Pattern
  • Null Object Pattern
  • Singleton Pattern
  • Observer Pattern (Listeners)
  • Template Method Pattern

The Challange

Ok, let's get to an apparently simple, but real project. Imagine you have the following challange:

You have 4 buttons on a toolbar on the bottom of your application. Every button starts its own animation  when it is tapped (let's say it is moved upward to show its activity) and after its animation is done, a second animation starts. (let's say a column is slided out showing icons on it). Can you imagine it? something like this:

Sketch

The requirements

Ok, let's move on. Here are futher requirements:
  • Every animation has to be synchronized which means, if an animation is running, none of the other animations can be started, till it ends. 
  • After every transition (animation) we should have the possibility of excuting some actions if we need. (let's say play a sound or execute a desired action)
  • Every button must be locked to each other. This means, if i press and hold one button, i can't fire another action by pressing anoter button.
  • If we touch the screen and an animation is showing already, this animation will slide back and a defined dafault button will be selected. (will be moved a little bit upward)

How can i identify the patterns now?

Know that we have sketched the scenarios and have listed the requirements, how can we identify proper pattern to use in this case?

Well, what i have done was to simple imagine the five buttons as a TV-Remote control and the animations as transition states on my screen. Doing that way it was almost impossible to not see the patterns. So i thought i had commands to start the animations (Command Pattern) and i thought i had states to represent any animation's transition. (State Pattern) - The key to this was the sketch i made. Imagine: Without it, it would be almost impossible to see it.

We should give the possibility to fire actions between states. And because this should be only possibilities, i can imagine scenarios in which there will be no actions also possible right? And here they are: NullState, NullAction and NullCommand. (Null Object Pattern)

Ok let's think further. As a requirement we must ensure singularity to any button. So i automatically see the picture of a lock, because there should be only one way to start actions. In that case we need a global accessible but unique flag to control that. (Synchronized Singleton Pattern)

And last but not least, as we will be dealing with a lot of action listeners and because of the button's synchronization, it would be necessary to implement a lot of individual Listeners for every button. If we do that way, we would end up with a bunch of duplicated code lines. For this reason we should implement an adapter of the TouchListener in which we place the lock logic in central unique place (Template Method Pattern), making it available for all buttons in the aplication. (Adapter Pattern). So i ended up with a simple but very usefull class diagram like that bellow which i used to define the app's architecture (structural part of it):

initial class diagram

Conclusion

In my opinion at least two things are indispensable in the process of figuring out what design pattern to apply:
  • a sketch 
  • as many requirements as available

Share your expirience

If you know other simple, practical ways on how to find out which design pattern to use, please feel free to contact me and share your thoughts.  It would be great to se the usage of other pattern in practise. (real projects) like i did. That's all. hope you like it.

😱👇 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘‡

Be sure to read, it will change your life!
Show your work by Austin Kleonhttps://amzn.to/34NVmwx

This book is a must read - it will put you in another level! (Expert)
Agile Software Development, Principles, Patterns, and Practiceshttps://amzn.to/30WQSm2

Write cleaner code and stand out!
Clean Code - A Handbook of Agile Software Craftsmanship: https://amzn.to/33RvaSv

This book is very practical, straightforward and to the point! Worth every penny!
Kotlin for Android App Development (Developer's Library): https://amzn.to/33VZ6gp

Needless to say, these are top right?

😱👆 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘†