Showing posts with label best practise. Show all posts
Showing posts with label best practise. Show all posts

Tuesday, August 12, 2014

Programming Design Pattern - Proxy Pattern Applied - Best Practise

Hi there!

Today i'm gonna show the proxy design pattern in action. The proxy is definitely not as present in our daily work as the other design patterns already presented. But it also has its purpose. Especially when it comes to security, remote accesses or processing heavy weight tasks in background without exposing the real implementation of it.

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 Proxy 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 Credentials

In the example bellow we will simulate a login access. For this reason let's define the credentials first.

public class Credential {
    private String username;
    private String password;
    public Credential(String username, String password) {
        this.username = username;this.password = password;
    }
    public String getUsername() {return username;}
    public void setUsername(String username) {this.username = username;}
    public String getPassword() {return password;}
    public void setPassword(String password) {this.password = password;}
}
public class SystemCredential {
    private Credential credential;
    private String username;
    private String password;
    public SystemCredential(Credential credential) {
        this.credential=credential;
        // simulating db or whatever access and getting system user info
        this.username = "sysAdmim";
        this.password = "sysPwd";
    }
    public boolean canAccess(){
        final boolean isUsernameOK = username.equals(credential.getUsername());
        final boolean isPasswordOK = password.equals(credential.getPassword());
        boolean sucess = isUsernameOK && isPasswordOK;
        if(sucess){
            // set flag in db or anywhere else (userAccessExpired=false) 
            // and start userAccessCountDown till session expires or user logs off.
        }return sucess;
    }
}

The Access Interface

This is the real access implementation. This is the structure responsible for the login process.

// SUBJECT
public interface Access {
    public boolean access(Credential credential);
    public boolean isExpired(Credential credential);
}
// REAL SUBJECT - DOES THE HEAVY WEIGHTING WORK
public class Login implements Access {
    @Override
    public boolean access(Credential credential) {
         return new SystemCredential(credential).canAccess();
    }
    public boolean isExpired(Credential credential) {
        // simulating db or whatever request to check this...
        final Random random = new Random();
        final int nextInt = random.nextInt(2);
        return nextInt==0?true:false;
    }
}

The Proxy

The proxy sends requests to the real implementation. The user thinks he is dealing with the real implementation while it is not.

// PROXY SENDS REQUESTS TO THE REAL SUBJECT (Login) MAKING ACCESSES EFFECTIVELY
public class LoginProxy implements Access {
    private Access user =  new Login();
    @Override
    public boolean access(Credential credential) {
//        if(!isExpired(credential)){
//            return true;
//        }return user.access(credential);
        return user.access(credential);
    }
    @Override
    public boolean isExpired(Credential credential) {
        return user.isExpired(credential);
    }
}

Testing it

Here we simulate what really happens. The only thing the user knows is the common interface Access.

public class Client {
    public static void main(String[] args) {
        Access login =  new LoginProxy();
        final Credential wrongCredential = new Credential("username", "password");
        final Credential rightCredential = new Credential("sysAdmim", "sysPwd");
        loginStatus(login, wrongCredential);
        loginStatus(login, rightCredential);
    }
    private static void loginStatus(Access login, final Credential credential) {
        boolean access = login.access(credential);
        if(access){System.out.println("Logget In: true");}
        else{System.out.println("Logged In: false");}
    }
}

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 - 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 ðŸ˜±ðŸ‘†

Programming Design Pattern - Builder Pattern Applied - Best Practise

Hi there!

Today i'm gonna share the first of a brand new programming design pattern series i made. The builder pattern is a very useful and common pattern while developing serious apps. In this post i'll give a tiny builder pattern framework, so you can always come back here and get it to work with.

A mnemonic, while dealing with builder pattern, is to think about customization. I always think about it, when i'm figuring out if i should use it or if i better take a factory. That's the way it works better for me. try yourself.

The UML Builder Pattern

Here is how the little framework looks like. Simple, nice and straightforward.


The code behind it

The code is also very simple, small, clean and self-explanatory. I like to code expressive, so i don't need to comment a lot. In this sample here i did, because it has a tutorial character. While developing i created some convention to my self. I think it is very important to do so. It is like applying the right grammar on a language while developing. 

For example: If i'm using the Builder Pattern, i always put the suffix Builder at the end. Well you may say or think now: what? But thats in fact a very, very, important info for beginners and expirienced developers. They will automatically see the idea behind it and will try not to break the pattern. In fact expirienced developers will love it and try to continue a good work, because they know, that the developer who wrote this, knows what he did and for sure there was a reason for it.

So always try to be clear enough and give the right information on the right places. Someone else will thank you later.  But now to the code... :)

// 1. EXAMPLE: PARTS OF THE CUSTOMIZABLE PRODUCT WE WANT
public interface Part {
    // DEFINE THE METHODS YOUR PARTS WILL HAVE...
    void anyMethodNameYouLike();
}

// 2. THE BUILDER METHOD WILL ADD 
// PARTS RETURNING THE BUILDER ITSELF
public interface BuildContract < B > {
    B mount(Part part);
}

// 3. DEFINE THE BUILDER'S CONTRUCTION METHOD
// WHICH BUILDS AND RETURNS THE FINAL PRODUCT "T"
public interface Builder < T > extends BuildContract < Builder < T > > {
    T build();
}

A real example

Nothing better then that to fix it and understand it better. Let´s implement a cake bakery. A colleague of yours wants to open a bakery and asked you to program a bakery's software for him. Let's do it.. :)
And by the way, I commend you heartily, using a UML diagram tool is as visualization mechanism to show your ideas and improve your design skills. Lets start by the UML:


The analogy

Let's now use our tiny framework and make the analogy for our bakery. Ingredient is the Part, Recipe is the BuilderContract and  Builder is the builder itself. Cake is the final, customizable product. CakeBuilder is the class which actually creates the product after customization (after the addition of as many parts - ingredients - as you want). The client would be the final client or your colleague taking the order. Just use or imagination... :) Let's dive into code now... 

The Ingredients (Parts)

The parts in our example are the ingredients. Let's implement some ingredients to use it later to make a cake. 
 
// 1. EXAMPLE: PART TO CUSTOMIZATE "INGREDIENTS"
public interface Ingredient {
    // INGREDIENTS WILL HAVE...
    void printName();
    String getUnitPrice();
    void printCalories();
}
public class LightMilk implements Ingredient {

    private int deciLiter;
    private int calories;
    private String unitPrice;
    
    public LightMilk(int deciLiter){this.deciLiter=deciLiter;}
    
    public LightMilk(int deciLiter, int calories, String unitPrice) {
        super();
        this.deciLiter = deciLiter;
        this.calories = calories;
        this.unitPrice = unitPrice;
    }

    @Override public void printName() {System.out.printf(" Light Milk");}
    @Override public String getUnitPrice() {return unitPrice;}
    @Override public void printCalories() {System.out.printf(" 76kc");}
    public int getDeciLiter() {return deciLiter;}
    public void setDeciLiter(int deciLiter) {this.deciLiter = deciLiter;}
    public int getCalories() {return calories;}
    public void setCalories(int calories) {this.calories = calories;}
    public void setUnitPrice(String unitPrice) {this.unitPrice = unitPrice;}
}
public class Sugar implements Ingredient {

    private int gram;
    private int calories;
    private String unitPrice;
    
    public Sugar(int deciLiter){this.gram=deciLiter;}
    
    public Sugar(int gram, int calories, String unitPrice) {
        super();
        this.gram = gram;
        this.calories = calories;
        this.unitPrice = unitPrice;
    }

    @Override public void printName() {System.out.printf(" Sugar");}
    @Override public String getUnitPrice() {return unitPrice;}
    @Override public void printCalories() {System.out.printf(" 40kc");}
    public int getGram() {return gram;}
    public void setGram(int gram) {this.gram = gram;}
    public int getCalories() {return calories;}
    public void setCalories(int calories) {this.calories = calories;}
    public void setUnitPrice(String unitPrice) {this.unitPrice = unitPrice;}
}
public class Choco implements Ingredient {
    private int gram;
    private int calories;
    private String unitPrice;
    public Choco(int gram, int calories, String unitPrice) {
        super();
        this.gram = gram;
        this.calories = calories;
        this.unitPrice = unitPrice;
    }
    public int getGram() {return gram;}
    public void setGram(int gram) {this.gram = gram;}
    public int getCalories() {return calories;}
    public void setCalories(int calories) {this.calories = calories;}
    public void setUnitPrice(String unitPrice) {this.unitPrice = unitPrice;}

    @Override public void printName() {System.out.printf(" Chocolate");}
    @Override public void printCalories() {System.out.printf(" 389kc");}
    @Override public String getUnitPrice() {return unitPrice;}
}
public class NoSugar implements Ingredient {

    private int gram;
    private int calories;
    private String unitPrice;
    
    public NoSugar(int deciLiter){this.gram=deciLiter;}
    
    public NoSugar(int gram, int calories, String unitPrice) {
        super();
        this.gram = gram;
        this.calories = calories;
        this.unitPrice = unitPrice;
    }

    @Override public void printName() {System.out.printf(" No Sugar");}
    @Override public String getUnitPrice() {return unitPrice;}
    @Override public void printCalories() {System.out.printf(" 0kc");}
    public int getGram() {return gram;}
    public void setGram(int gram) {this.gram = gram;}
    public int getCalories() {return calories;}
    public void setCalories(int calories) {this.calories = calories;}
    public void setUnitPrice(String unitPrice) {this.unitPrice = unitPrice;}
}
public class Milk implements Ingredient {

    private int deciLiter;
    private int calories;
    private String unitPrice;
    
    public Milk(int deciLiter){this.deciLiter=deciLiter;}
    
    public Milk(int deciLiter, int calories, String unitPrice) {
        super();
        this.deciLiter = deciLiter;
        this.calories = calories;
        this.unitPrice = unitPrice;
    }

    @Override public void printName() {System.out.printf(" Milk");}
    @Override public String getUnitPrice() {return unitPrice;}
    @Override public void printCalories() {System.out.printf(" 128kc");}
    public int getDeciLiter() {return deciLiter;}
    public void setDeciLiter(int deciLiter) {this.deciLiter = deciLiter;}
    public int getCalories() {return calories;}
    public void setCalories(int calories) {this.calories = calories;}
    public void setUnitPrice(String unitPrice) {this.unitPrice = unitPrice;}
}

The Builder's Contract

This is the Recipe in our example.

// 2. THE BUILDER METHOD WILL ADD 
// INGREDIENTS RETURNING THE BUILDER ITSELF
public interface Recipe < B > {
    B addIngredient(Ingredient ingredient);
}
// 3. DEFINE THE BUILDER CONTRUCTION METHOD
// WHICH BUILDS AND RETURNS THE FINAL PRODUCT "T"
public interface Builder < T > extends Recipe < Builder < T > > {
    T build();
}
import java.util.ArrayList;
import java.util.List;
// 4. IMPLEMENT THE BUILDER ACC. TO YOUR NEEDS
public class CakeBuilder implements Builder < Cake > {
    // IN THIS CASE THE PARTS ARE THE INGREDIENTS
    private List < Ingredient > ingredients=new ArrayList < Ingredient > ( );
    @Override
    public Cake build() {
        if(!ingredients.isEmpty()){
            // THE FINAL PRODUCT IS A CHOCO-MUFFIN
            return new Cake(ingredients);
        }
        return new Cake(null);
    }
    @Override
    // BECAUSE I ALWAYS GET A BUILDER BACK, I'M ABLE TO
    // ADD A LOT OF PARTS BEFORE I CALL "BUILD()"
    public Builder < Cake > addIngredient(Ingredient ingredient) {
        if(ingredient!=null){
            ingredients.add(ingredient);
        }
        return this;
    }
}

The product

In our example the product to build is a cake.
import java.util.List;

public class Cake {
    public Cake(List < Ingredient > ingredients){
        String muffin = "";
        if(ingredients==null){
            System.out.println(" zero cake "+muffin);
            return;
        }
        // PRINT OUT MUFFIN INGREDIENTS
        System.out.printf(" Cake with: ");
        for (Ingredient ingredient : ingredients) {
            ingredient.printName();
        }
        // PRINT OUT PART PRICES
        for (Ingredient ingredient : ingredients) {
            muffin+=" "+ingredient.getUnitPrice();//NOPMD
        }
        System.out.println(" - Price: "+muffin);
    }
    public void printResult(){
        System.out.println(" Cake is ready!");
    }
}

Testing it

Finally the client test. Here we can see the usage of it:
// 5. TESTING THE CHOCO-BUILDER
public class Client {
    public static void main(String[] args) {
        Builder < Cake > chocoMuffinBuilder = new CakeBuilder();
        chocoMuffinBuilder.addIngredient(new Choco(10, 23, "3.39"));
        chocoMuffinBuilder.addIngredient(new Milk(34, 67, "1.57"));
        chocoMuffinBuilder.addIngredient(new Sugar(34, 67, "2.00"));
        final Cake chocoMuffin = chocoMuffinBuilder.build();
        chocoMuffin.printResult();
    }
}
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 ðŸ˜±ðŸ‘†