Tuesday, August 12, 2014

Programming Design Pattern - Template Method Applied - Best Practise

Hi there!

Today i'm gonna show the template method design pattern in action. The template method design pattern is a very common when we are developing structures and base classes for a framework.

I'm assuming here you already know the concepts and i'll be focusing on practise. The example i will provide is a nice way to show it how it could looks like. You can always come back here, take it, adapt it and use it in your applictions as you may need. So be sure you bookmark it or join the group here on the right side of this post subscribing it.

First of all, let's take a look at the UML diagram of it. After that we will take the analogy for our example.

The UML diagram of the Template Method Pattern

Pay close attention, because once you understand that, everything will become clear and simple to understand. That's the reason I'm putting always the UML first. That way you'll get an eye for it with the time.


Why use it?

In our example we will develop a base class with some template methods for all derived concrete calculators. But what are template methods and why shall i use it? Well, think about some operations that must be implemented in a specific way. And you want to ensure it. That's a good reason for it. Another reason is to define the same contract for all instances. And finally because of the DRY principle. (Don't Repeat Yourself) The abstraction will put the code in a central place. This is good for maintance.

public abstract class CalculatorTemplate {
   public double multiply(double a, double b){
       double posA= getPositiveValueOf(a);
       double posB= getPositiveValueOf(b);
       return posA*posB;
   }
   public double substract(double a, double b){
       double posA= getPositiveValueOf(a);
       double posB= getPositiveValueOf(b);
       double greater = getGreaterValueOf(posA,posB);
       double smaller = getSmallerValueOf(posA,posB);
       return greater-smaller;
   }
   // 1. DEFINING THE TEMPLATES
   protected abstract double getSmallerValueOf(double a, double b);
   protected abstract double getGreaterValueOf(double a, double b);
   protected abstract double getPositiveValueOf(double n);
}

Concrete implementation

A further advantage of it is that the javadoc can be placed in the abstraction only once and must not be repeated also in the concrete implementations. Now let's say you want to implement a bunch of different looking calculators. With this abstraction you could it.

// 2. IMPLEMENTING THE TEMPLATES
public class Calculator extends CalculatorTemplate {
    @Override
    protected double getSmallerValueOf(double a, double b) {
        final int compareTo = Double.valueOf(a).compareTo(Double.valueOf(b));
        return compareTo > 0 ? a : b ;
    }
    @Override
    protected double getPositiveValueOf(double n) {
        return Double.valueOf(String.valueOf(n).replaceAll("-", ""));
    }
}

Testing it

Finally let's test it.
public class Client {
    public static void main(String[] args) {
        System.out.println("substraction: "+new Calculator().substract(50, -2));
        System.out.println("multiplication: "+new Calculator().multiply(-2, 50));
    }
}

That's all! I 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?
Apple AirPods Pro: https://amzn.to/2GOICxy

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

Programming Design Pattern - Visitor Pattern Applied - Best Practise

Hi there!

Today i'm gonna show the visitor design pattern in action. The visitor design pattern is a very useful programming design pattern while dealing with responsibilities that are not part of an exsiting implementation.

I'm assuming here you already know the concepts and i'll be focusing on practise. The example i will provide is a nice way to show it how it could looks like. You can always come back here, take it, adapt it and use it in your applictions as you may need. So be sure you bookmark it or join the group here on the right side of this post subscribing it.

First of all, let's take a look at the UML diagram of it. After that we will take the analogy for our example.

The UML Diagram of the Visitor Pattern


Pay close attention, because once you understand that, everything will become clear and simple to understand. That's the reason I'm putting always the UML first. That way you'll get an eye for it with the time.


The visitor and visitable

In the example bellow, we will use the visitor to extract information from an existing car structure. Let's say you have a program with deals with a lot of different vehicles registering it and storing information about it. We will use it, to extract some information, that is not part of the responsibility from this structure. Here we define the necessary interfaces and classes to implement it.

public interface Visitor {
    < T extends Visitable > void visit(T visitable, VisitableType type);
}
public interface Visitable {
    < T extends Visitor > void accept(T visitor);
}
public enum VisitableType {
    CAR, BUS, TRUCK;
}

The concrete visitable

Those classes are the instances who accepts visitors. Let's see how they are implemented...

public class Bus implements Visitable {
    @Override
    public < T extends Visitor > void accept(T visitor) {
        visitor.visit(this, VisitableType.BUS);
    }
    public void fuelType(){
        System.out.println("Bus> Fuel: Gas");
    }
}
public class Car implements Visitable {
    @Override
    public < T extends Visitor > void accept(T visitor) {
        visitor.visit(this, VisitableType.CAR);
    }
    public void fuelType(){
        System.out.println("Car > Fuel: Gasoline and Alcohol");
    }
}
public class Truck implements Visitable {
    @Override
    public < T extends Visitor > void accept(T visitor) {
        visitor.visit(this, VisitableType.TRUCK);
    }
    public void fuelType(){
        System.out.println("Truck> Fuel: Diesel");
    }
}

The concrete visitors

When the visitables accepts some visitor, they imediatelly calls the method visit from it passing itself to it. This way, the visitors can use some attributes of it to extract infos or to process what ever you need to process. Let's take a look inside of it to understand it.

// VISITOR
public class Fuel implements Visitor {
    @Override
    public < T extends Visitable > void visit(T visitable, VisitableType type) {
        switch (type) {
        case CAR:
            ((Car)visitable).fuelType();
            break;
        case BUS:
            ((Bus)visitable).fuelType();
            break;
        case TRUCK:
            ((Truck)visitable).fuelType();
            break;
        default:
            break;
}}}

Testing it

The test bellow shows the visitor in action. We are extracting infos from the cars and showing to the user.

public class Client {
    public static void main(String[] args) {
        // VISITOR
        final Visitor info = new Fuel();
        // VISITABLES
        final Visitable car = new Car();
        final Visitable truck = new Truck();
        final Visitable bus = new Bus();
        // VISITING VISITABLES
        car.accept(info);
        truck.accept(info);
        bus.accept(info);
    }
}

That's all! I 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?
Apple AirPods Pro: https://amzn.to/2GOICxy

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

Programming Design Pattern - Strategy Pattern Applied - Best Practise

Hi there!

Today i'm gonna show the strategy design pattern in action. The strategy design pattern is a very useful programming design pattern while dealing with mutable behaviors.

I'm assuming here you already know the concepts and i'll be focusing on practise. The example i will provide is a nice way to show it how it could looks like. You can always come back here, take it, adapt it and use it in your applictions as you may need. So be sure you bookmark it or join the group here on the right side of this post subscribing it.

First of all, let's take a look at the UML diagram of it. After that we will take the analogy for our example.

The UML diagram of the Strategy Pattern

Pay close attention, because once you understand that, everything will become clear and simple to understand. That's the reason I'm putting always the UML first. That way you'll get an eye for it with the time.


Defining the strategy

That's the part a like the most. Designing, taking decissions, doing analysis and design like you've learned in the past, but applying now in the practise. At this point, you should separate the 'inmutable' from the 'mutable' behaviors. In our case, this is the weapon behavior, that can vary acc. to the game stage we are. The imutable is the warrior which just references to the strategy.

// 1. DEFINE THE STRATEGY
public interface WeaponBehavior {
    void fire();
}
// 2. DEFINE THE WARRIOR AND USE
//    THE MUTABLE BEHAVIORS
public abstract class Warrior {
    // USE MUTABLE WEAPON BEHAVIORS
    protected WeaponBehavior weapon;
    
    public Warrior() {
        super();
        this.weapon = new DefaultWeapon();
    }
    public void setWeapon(WeaponBehavior weapon){
        this.weapon=weapon;
    }
    public void fireWeapon(){
        this.weapon.fire();
    }
    public abstract void fight();
}

The Warrior

The warrior can set weapons and fires it acc. to the used strategy. That's a very simple implementation.

// 3. CREATE THE CONCRETE WARRIOR
public class MegaMan extends Warrior {
    @Override
    public void fight() {
        fireWeapon();
        // ... outros metodos de escudo, briga etc. aqui...
    }
}

Weapons

That's the mutable behavior. The interesting part of it. Let's implement some weapon strategies.

// 4. IMPLEMENT THE WEAPON BEHAVIORS
public class Bee implements WeaponBehavior {
    @Override
    public void fire() {
        System.out.println("BEE ATACK!");
    }
}
public class Scissors implements WeaponBehavior {
    @Override
    public void fire() {
        System.out.println("SCISSORS ATACK!");
    }
}
public class DefaultWeapon implements WeaponBehavior {
    @Override
    public void fire() {
        System.out.println("DEFAULT ATTACK");
    }
}

Testing it

Our client tests it. Pay attention that we do not change the inmutable warrior, only its weapon strategy.

public class Client {
    public static void main(String[] args) {
        MegaMan megaMan = new MegaMan();
        megaMan.fight();
        // USING STRATEGIES
        // FIRST WEAPON OF TYPE SCISSORS
        megaMan.setWeapon(new Scissors());
        megaMan.fight();
        // CHANGING STRATEGIES
        // SECOND WEAPON OF THE TIPE BEE
        megaMan.setWeapon(new Bee());
        megaMan.fight();
    }
}

That's all! I 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?
Apple AirPods Pro: https://amzn.to/2GOICxy

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

Programming Design Pattern - Singleton Pattern Applied - Best Practise

Hi there!

Today i'm gonna show the singleton design pattern in action. The singleton design pattern is a largely used and common programming design pattern while dealing with uniqueness in your application.

I'm assuming here you already know the concepts and i'll be focusing on practise. The example i will provide is a nice way to show it how it could looks like. You can always come back here, take it, adapt it and use it in your applictions as you may need. So be sure you bookmark it or join the group here on the right side of this post subscribing it.

First of all, let's take a look at the UML diagram of it. After that we will take the analogy for our example.

The simpliest UML - Singleton Pattern


Pay close attention, because once you understand that, everything will become clear and simple to understand. That's the reason I'm putting always the UML first. That way you'll get an eye for it with the time.

The Singleton

This is a very common design pattern and largely used with most applications out there. It's important to know this pattern, because you'll see it a lot of times during your programming life. There are, so far as i know, four categories of singletons. Synchronized, not synchronized, lazy, and not lazy initialized. The way you can construct it is largely discussed. You may use an enum or a normal class. In the example bellow i used a normal class.

public final class Session 
{
    private static Session instance;
    /** singleton */
    private Session() {}
    /** if you do not need synchronization do not mark it as synchronized */
    public synchronized static Session getInstance() 
    {
        return (instance == null) ? instance = new Session() : instance;
    }
    /** your methods goes here... */
 }

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?
Apple AirPods Pro: https://amzn.to/2GOICxy

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

Programming Design Pattern - State Pattern Applied - Best Practise

Hi there!

Today i'm gonna show the state design pattern in action. The state design pattern is a very useful programming design pattern while dealing with state maschines.

I'm assuming here you already know the concepts and i'll be focusing on practise. The example i will provide is a nice way to show it how it could looks like. You can always come back here, take it, adapt it and use it in your applictions as you may need. So be sure you bookmark it or join the group here on the right side of this post subscribing it.

First of all, let's take a look at the UML diagram of it. After that we will take the analogy for our example.

The simpliest UML State Pattern

Pay close attention, because once you understand that, everything will become clear and simple to understand. That's the reason I'm putting always the UML first. That way you'll get an eye for it with the time.

The State Interface

Here we can see how simple it is. Let's implement some real states from our ticket automat to get more familiar with. The MoneyState will be set, when the user has paid for the ticket and will calculate the exchange if some.

public interface State {
    void handle();
}
public class MoneyState implements State {
    private TicketAutomat context;
    public MoneyState(TicketAutomat context) {
        this.context = context;
    }
    @Override
    public void handle() {
        System.out.println("PAYMENT RECEIVED! CALCULATING EXCHANGE ...");
        context.setCurrentState(context.getSoldState());
        context.getCurrentState().handle();
    }
}

The TicketSoldState

This state says to the user that the ticket has been sold out successfully and sets the NoMoneyState asking the user to pay for a ticket if we still have tickets available, otherwise will set the SoldOutStore which shows to the user, that all tickets are sold out.

public class TicketSoldState implements State {
    private TicketAutomat context;
    public TicketSoldState(TicketAutomat context) {
        this.context = context;
    }
    @Override
    public void handle() {
        context.updateTicketsAvailable();
        context.setPaid(false);
        System.out.println("YOUR TICKET WAS PRINTED OUT!");
        if(context.isTicketAvailable()){
            context.setCurrentState(context.getNoMoneyState());
        }else{
            context.setCurrentState(context.getSoldOutState());
            context.getCurrentState().handle();
        }
    }
}

TicketsSoldOutState

This state says, "Sorry no more tickets available" or sets the NoMoneyState if we have tickets available.

public class TicketsSoldOutState implements State {
    private TicketAutomat context;
    public TicketsSoldOutState(TicketAutomat context) {
        this.context = context;
    }
    @Override
    public void handle() {
        if(context.isTicketAvailable()){
            context.getNoMoneyState().handle();
        }else{
            System.out.println("SORRY! THERE IS NO MORE TICKETS AVAILABLE!");
            context.setCurrentState(context.getSoldOutState()); 
        }
    }
}

NoMoneyState

This state is the first message the user will see, if we have tickets to sell. It sets the MoneyState to show to the user, that it has received the money and it is processing it.

public class NoMoneyState implements State {
    private TicketAutomat context;
    public NoMoneyState(TicketAutomat context) {
        this.context = context;
    }
    @Override
    public void handle() {
        System.out.println("PLEASE PAY FOR THE TICKET YOU WANT!");
        context.setCurrentState(context.getMoneyState());
        context.getCurrentState().handle();
    }
}

The Context - TicketAutomat

This is the context class. It contais all states and has the some simple logic in it

// THE TICKET AUTOMAT IS THE CONTEXT
public class TicketAutomat {
    
    private State soldOutState;
    private State noMoneyState;
    private State moneyState;
    private State soldState;
    private State currentState;
    
    private int ticketsAvailable = 10;
    private boolean paid=false;
    
    TicketAutomat(int ticketsAvailable){
        soldState =  new TicketSoldState(this);
        soldOutState =  new TicketsSoldOutState(this);
        noMoneyState =  new NoMoneyState(this);
        moneyState =  new MoneyState(this);
        initCurrentState(ticketsAvailable);
    }
    
    private void initCurrentState(int ticketsAvailable){
        this.ticketsAvailable=ticketsAvailable;
        if(this.ticketsAvailable>0){
            setCurrentState(noMoneyState);
        }else{
            setCurrentState(soldOutState);
        }
    }
        
    public State getSoldOutState() {return soldOutState;}
    public State getNoMoneyState() {return noMoneyState;}
    public State getMoneyState() {return moneyState;}
    public State getSoldState() {return soldState;}
    public State getCurrentState() {return currentState;}
    public void setCurrentState(State currentState) {this.currentState = currentState;}
    public int getTicketsAvailable() {return ticketsAvailable;}
    public void setTicketsAvailable(int ticketsAvailable) {this.ticketsAvailable = ticketsAvailable;}
    public void updateTicketsAvailable(){this.ticketsAvailable-=1;}
    public boolean isTicketAvailable(){return this.ticketsAvailable>0;}
    public boolean hasPaid(){return paid;}
    public void setPaid(boolean paid){this.paid=paid;}
}

Testing it

Finally our client which tests it. With a Thread we are simulating a full cycle waiting 5 seconds between each state.

public class Client {
    public static void main(String[] args) {
        new Thread(){
            int ticketsAvailable = 5;
            final TicketAutomat automat = new TicketAutomat(ticketsAvailable);
            public void run() {
                while(automat.isTicketAvailable()){
                    automat.setPaid(true);
                    automat.getCurrentState().handle();
                    try {
                        sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            };
        }.start();
    }
}
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?
Apple AirPods Pro: https://amzn.to/2GOICxy

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

Friday, August 8, 2014

Programming Design Pattern - Decorator Pattern Applied - Best Practise

Hi there!

Today i'm gonna show the decorator design pattern in action. The decorator design pattern is a largelly used programming design pattern while dealing with grafics, trees and dynamic changes during runtime.

It is also a greate choice if you are looking or trying to do recursion with. I love it. In this post we will implement a students decoration. We will decorate it with degrees and doctor titles. A nice example to see how it works in the real world.

First of all, let's take a look at the UML diagram of it in its simpliest variety. After that we will take the analogy for our example.

The simpliest UML Decorator Pattern

Pay close attention, because once you understand that, everything will become clear and simple to understand. That's the reason I'm putting the simplest model here first.

Understanding the Details

The decorable will be every concrete implementation of the common interace Decorable. The decorators will be every implementation of the abstract class Decorator. Which defines the decorator's contract holding an instance to decorables. Let's dive into some code to fix it:
 
// 1. COMMON INTERFACE FOR DECORABLES
public interface Decorable {
    public String getDescription();
}
// 2. THE ABSTRACT DECORADOR WHICH HOLDS A REFERENCE TO DECORABLES
public abstract class Decorator implements Decorable {
    protected Decorable component;
    public Decorator(Decorable component){
        super();
        this.component=component;
    }
}

The Analogy to our Students example

Let's start again with the UML diagram first:

The common decorable Girl

Here we start with the analogies. The interface Girl is the decorable. GirlDecorator defines the abstract decorator's contract with the concrete decorators bellow.

// 1. COMMON INTERFACE FOR DECORABLES
public interface Girl {
    public String getDescription();
}
// 2. THE ABSTRACT DECORADOR WHICH HOLDS A REFERENCE TO DECORABLES 
public abstract class GirlDecorator implements Girl {
    protected Girl girl;
    public GirlDecorator(Girl girl){
        super();
        this.girl=girl;
    }
}
// 3. DEFINING CONCRETE DECORATORS
public class Science extends GirlDecorator {
    public Science(Girl girl) {super(girl);}
    @Override
    public String getDescription() {
        // DECORATES WITH A SCIENCE'S DEGREE
        return girl.getDescription() + "+Like Science";
    }
    public void caltulateStuff() {
        // ADDS NEW FEATURES (METHOD) TO IT
        System.out.println("scientific calculation!");
    }
}
public class Art extends GirlDecorator {
    public Art(Girl girl) {super(girl);}
    @Override public String getDescription() {return girl.getDescription() + "+Like Art";}
    public void draw() {System.out.println("draw pictures!");}
}
public class Doctor extends GirlDecorator {
    public Doctor(Girl girl) {super(girl);}
    @Override public String getDescription() {return girl.getDescription() + "+Like Doctor";}
    public void calculateStuff() {System.out.println("doctor calculation!");}
    public void doctorTitle() {System.out.println("doctor title");}
}

The Decorables

AmericanGirl and EuropeanGirl are the decorable that will be decorated with degrees and doctor tittles at runtime enhancing its curriculum and abilities.

// 4. AN AMERICAN GIRL WILL BE DEFINED AS A DECORABLE
public class AmericanGirl implements Girl {
    private String description="";
    // NORMAL AMERICAN GIRL
    public AmericanGirl(){
        super();
        description = "+American";
    }
    @Override public String getDescription() {return description;}
}
public class EuropeanGirl implements Girl {
    private String description="";
    public EuropeanGirl() {
        super();
        description = "+European";
    }
    @Override public String getDescription() {return description;}
}

Testing it

Now let's see in practise how it looks like. How we can decorate and enhance its abilities at runtime

public class Client {
    public static void main(String[] args) {
        // COMMOM GIRL
        Girl girl;
        
        // CREATING NORMAL AMERICAN GIRL
        girl = new AmericanGirl();
        System.out.println(girl.getDescription());
 
        // DECORANTING AMERICANA GIRL WITH SCIENCE'S DEGREE
        girl = new Science(girl);
        System.out.println(girl.getDescription());
 
        // DECORANTING AMERICANA GIRL WITH ART'S DEGREE
        girl = new Art(girl);
        System.out.println(girl.getDescription());
        
        // EUROPEAN GIRL HAS ALREADY ALL DEGREES   
        Girl europeia = new Science(new Art(new EuropeanGirl()));
        System.out.println(europeia.getDescription());
        
        // DOCTOR HAS NEW FUNCTIONS    
        girl = new Doctor(girl);
        System.out.println(girl.getDescription());
        // BECAUSE DOCTOR EXTENDS FROM COMMON GIRL, IT CAN DO A DOWNCAST
        ((Doctor)girl).doctorTitle();
        ((Doctor)girl).calculateStuff();
        
        // PAY ATTENTION THAT WE USE THE SAME INSTANCE, BUT THEY BEHAVIOR DIFFERENT
        // AT DIFFERENT TIME SLOTS. THE CLIENT HAS THE IMPRESSION THAT WE HAVE
        // CHANGED THE IMPLEMENTATION, BUT IN FACT NOT.
    }
}

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?
Apple AirPods Pro: https://amzn.to/2GOICxy

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

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?
Apple AirPods Pro: https://amzn.to/2GOICxy

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