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

Wednesday, May 11, 2016

How to define build strategies in your android app over BuildConfig

Hi there!

Today i'm gonna show you, how your could define your build strategies in android studio in an elegant, enhanceable way using the strategy design pattern.

Most of the times, Google defines its product making usage of best practises and good, enhanceable design pattern. I saw recently, in a big project we got, that they were not taking advantage of this and instead of that, they were using enumerations, resulting in a bunch of switch cases and later on another bunch of if-else cases and a lot of repeated code that breaks the DRY-principle and even more important the open-close-principle.

What does it mean to be programming respecting the open-close-principle? It means that every time a new component is created, that i don't have to change running code. i.e. I don't have to create another enum type, another switch-case to identify this type and later on another if-else case to know, depending on the comparation result, what kind of environment i want to set.

That's the code we got. This code has a lot of problems. It is fragile. Every new environment forces you to change a chain of steps in the code. Further it forces you to hold 4 variables in a static way to be able to share it over the application instead of hold only one object responsible for that. We define new enum types and define a new if statement running the risk of breaking existing logic. All of this can be avoided using the strategy pattern.

Let's take a look at the actual code, before enhancing it to visualize the problems:

    // somewhere in code this method was called passing the enum defined in BuildConfig
    setEnvironmentKeys(BuildConfig.ENVIRONMENT);
    // later in the class who defined this method over if-statements we identify the environment
    public static void setEnvironmentKeys(ENV env){
        try{
         if (MainApplication.isProduction()) {
                CONTENT_SERVER_URL = "https://content.mycompany.com/";
                PROFILE_SERVER_URL = "https://profile.mycompany.com/";
                IMAGE_SERVER_URL = "https://image.mycompany.com/log";
                Utils.GOOGLE_DEVELOPER_KEY = Utils.getStringRes(R.string.key_production);
            } else if (env == MainApplication.ENV.STAGING) {
                CONTENT_SERVER_URL = "http://content-staging.mycompany.com/";
                PROFILE_SERVER_URL = "http://profile-staging.mycompany.com/";
                IMAGE_SERVER_URL = "http://image.staging.maycompany.com/";
                Utils.GOOGLE_DEVELOPER_KEY = Utils.getStringRes(R.string.key_staging);
            }  else if (env == MainApplication.ENV.STAGING_TWO) {
                Utils.GOOGLE_DEVELOPER_KEY = Utils.getStringRes(R.string.key_staging);
                CONTENT_SERVER_URL = "http://content-staging2.mycompany.com/";
                PROFILE_SERVER_URL = "http://profile-staging2.mycompany.com/";
                IMAGE_SERVER_URL = "http://image.staging2.mycompany.com/";
            }else if (MainApplication.isDev()) {
                Utils.GOOGLE_DEVELOPER_KEY = Utils.getStringRes(R.string.key_development);
                CONTENT_SERVER_URL = "https://content.dev.mycompany.com/";
                PROFILE_SERVER_URL = "https://profile.dev.mycompany.com/";
                IMAGE_SERVER_URL = "https://image.dev.mycompany.com/";
            }
        }catch(Exception e){
            Log.wtf(TAG, "Couldn't set ENV variables. Setting to Production as default.");
        }
    }
    
    // and somewhere was defined the enum with the build types
    public enum ENV {
        DEVELOPMENT("DEVELOPMENT"),
        STAGING("STAGING"),
        STAGING_TWO("STAGING_TWO"),
        OPS_PREVIEW("OPS_PREVIEW"),
        PRODUCTION("PRODUCTION"), ;

        private final String name;

        private ENV(String s) {
            name = s;
        }

        public boolean equalsName(String otherName){
            return (otherName == null)? false:name.equals(otherName);
        }

        public String toString(){
            return name;
        }

    }

The code above is functional but when it comes to enhancement, maintainability and so on, then we can see some problems on that. We will discuss this later on. Let's now see how we could do it better by using the strategy pattern. First have a look at the uml diagram of it.



And now the little code of if:

   
  // this method is called somewhere in code
  setEnvironment(BuildConfig.ENVIRONMENT);
  
  // then we set the environment and use it without any change in code
  private Environment environment;
  public void setEnvironment(final Environment env){
   environment = env;
  }
  /**
   * In your android studio look for the tab: "Build Variants" (bottom left side)
   * and select "Build Variant > debug" while developing the application.
   * This will automatically instantiate this class and assign this value to BuildConfig.ENVIRONMENT
   * @author Ricardo Ferreira
   */
  public class DeveloperEnvironment extends Environment{
   private final static String CONTENT_SERVER_URL = "https://content.dev.mycompany.com/";
   private final static String PROFILE_SERVER_URL = "https://profile.dev.mycompany.com/";
   private final static String S3_AMAZON_SERVER_URL = "https://s3.amazon.dev.mycompany.com";
   private final static String GOOGLE_DEVELOPER_KEY = "123456";
   public DeveloperEnvironment() {
    super(CONTENT_SERVER_URL, PROFILE_SERVER_URL, S3_AMAZON_SERVER_URL, GOOGLE_DEVELOPER_KEY);
   }
  }
  /**
   * Build environment strategy - Every environment phase should extend from this strategy.
   * This way, you can access your app's environment configuration over the system class 
   * BuildConfig.ENVIRONMENT everywhere without the necessity of enumerations, switch cases 
   * or a bunch of if-else statements. If you create new environments, no change in your code
   * will be needed. 
   * @author Ricardo Ferreira
   */
  public abstract class Environment{
   private final String CONTENT_SERVER_URL;
   private final String PROFILE_SERVER_URL;
   private final String S3_AMAZON_SERVER_URL;
   private final String GOOGLE_DEVELOPER_KEY;
   // ... other environment variables ...
 public Environment(
   final String contentServerUrl, 
   final String profileServerUrl,
   final String s3amazonServerUrl, 
   final String googleDeveloperKey) {
  super();
  this.CONTENT_SERVER_URL = contentServerUrl;
  this.PROFILE_SERVER_URL = profileServerUrl;
  this.S3_AMAZON_SERVER_URL = s3amazonServerUrl;
  this.GOOGLE_DEVELOPER_KEY = googleDeveloperKey;
 }
 public String getContentServerUrl() {
  return CONTENT_SERVER_URL;
 }
 public String getProfileServerUrl() {
  return PROFILE_SERVER_URL;
 }
 public String getS3AmazonServerUrl() {
  return S3_AMAZON_SERVER_URL;
 }
 public String getGoogleDeveloperKey() {
  return GOOGLE_DEVELOPER_KEY;
 }
  }

Coming back to our initial discussion. Imagine now you need to add a new enviromnet. lets say staging. with the approach above you just have to say to someone: create a class who extends from environment, analogical DeveloperEnvironment, define it in your build.gradle, like you would do for the other approach also and done! It would work just fine without touching already written, functional code.The other way around you would have to change the enum, change the if-else statements.

Here is how you could define the strategies in your build.gradle. This will automatically assign the right value to the variable ENVIRONMENT depending on which environment you choose over Android Studio by selecting the tab Build Variants on the bottom left side of your IDE:

buildTypes {
        debug {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            debuggable true
            setApplicationIdSuffix("dev")
            versionNameSuffix " Dev"
            buildConfigField "com.treslines.learn.environment.Environment", "ENVIRONMENT", "new com.treslines.learn.environment.DeveloperEnvironment()"
            buildConfigField "boolean", "DEBUGLOG", "true"
            manifestPlaceholders = [
                    appName         : "MyApp Debug"
            ]
        }
        Staging {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.debug
            debuggable true
            setApplicationIdSuffix("staging")
            versionNameSuffix " Staging"
            buildConfigField "com.treslines.learn.environment.Environment", "ENVIRONMENT", "new com.treslines.learn.environment.StagingEnrivornment()"
            buildConfigField "boolean", "DEBUGLOG", "true"
            manifestPlaceholders = [
                    appName         : "MyApp Stg"
            ]
        }
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.release
            zipAlignEnabled true

            buildConfigField "com.treslines.learn.environment.Environment", "ENVIRONMENT", "new com.treslines.learn.environment.ProductionEnrivornment()"
            buildConfigField "boolean", "DEBUGLOG", "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 ðŸ˜±ðŸ‘†

Tuesday, August 11, 2015

Router Design Pattern - Route messages, Objects or whatever you want!

Hi there!

Today i'm gonna show you the router pattern i wrote myself in action. The Router design pattern is a very useful programming design pattern whenever you need to be able to send objects or messages between instances over the application.

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. If you use it anywhere, please come back and give me a feedback. It would be nice to have more real use cases.

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 Router 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 example

In our example we will see, how we could create clients that listen to server responses. The servers are lazy instantiated and are created on demand.

Response and Request Interfaces

Those interfaces defines a contract to be used to design which type the client will use to send requests and receive responses. Let's take a closer look to it:
public interface Response < T >  {
  T getResponse();
  void setResponse(T value);
}

public interface Request < T >  {
  T getRequest();
  void setRequest(T value);
}

Client and Server Interfaces

Those interfaces defines a contract to be used while implementing concrete clients and servers. It uses either the Response or the Request depending on the what you are implementing:
public interface Client {
   < T extends Response < ? >  >  void onServerResponse(T response);
}

public interface Server {
  < T extends Request < ? > > void onClientRequest(T request, Client client);
}

Routable interface and Router class

The routable defines the contract for the router. The router itself is designed as a singleton and can be accessed and used everywhere in the application sending and receiving messages or objects. In this implementation the servers are lazy implemented and created on demand. For sure you may adapt it to your needs. Feel free to do it and give me feedback of the usage of it in your applications.
public interface Routable {
  public  < T extends Client >  void registerClient(T clientImpl);
  public void registerServer(Class < ? extends Server >  serverImpl);
  public  < T extends Request < ? >  >  void routeClientToServer(Class < ? extends Client >  clientImpl, Class < ? extends Server >  serverImpl, T request);
  public void removeClient(Class < ? >  serverClass);
  public void removeAllClients();
  public void removeServer(Class < ? >  clientClass);
  public void removeAllServers();
  public boolean isRegistered(Class < ? >  clazz);
}


public class Router implements Routable {

  private Map < String, Client >  clients = new HashMap < String, Client > ();
  // using sets to avoid duplicates
  public Set < Class < ? extends Client >  >  clientSet = new HashSet < Class < ? extends Client >  > ();
  public Set < Class < ? extends Server >  >  serverSet = new HashSet < Class < ? extends Server >  > ();
  private static final Router ROUTER = new Router();

  private Router() {
    // singleton - can be accessed anywhere in the application
  }

  public static Router turnOn() {
    return ROUTER;
  }

  public  < T extends Request < ? >  >  void routeClientToServer(Class < ? extends Client >  clientImpl, Class < ? extends Server >  serverImpl, T request) {
    doNotAllowNullValue(clientImpl);
    doNotAllowNullValue(serverImpl);
    doNotAllowNullValue(request);
    doNotAllowUnregisteredNullValue(isRegistered(clientImpl));
    // just to ensure that the server implementation exits already
    doNotAllowUnregisteredNullValue(isRegistered(serverImpl));
    // as we now know that the server implementation exists,
    // we just create a lazy instance over reflection on demand
    try {
      serverImpl.newInstance().onClientRequest(request, clients.get(clientImpl.getName()));
    } catch (InstantiationException e) {
      // we shall never run into this situation, except if the user does NOT define
      // a default constructor in any of the concrete implementation of Server as per
      // convention.
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    }
  }

  public void removeServer(Class < ? >  serverClass) {
    serverSet.remove(serverClass);
  }

  public void removeAllServers() {
    serverSet.clear();
  }

  public void removeClient(Class < ? >  clientclass) {
    clients.remove(clientclass.getName());
    clientSet.remove(clientclass);
  }

  public void removeAllClients() {
    clients.clear();
  }

  public boolean isRegistered(Class < ? >  clazz) {
    boolean result = false;
    boolean searchBreak = false;
    Iterator < Class < ? extends Client >  >  iterator = clientSet.iterator();
    while (iterator.hasNext()) {
      Class < ? extends Client >  next = iterator.next();
      // note: we can't use equalsIgnoreCase here
      if (next.getName().equals(clazz.getName())) {
        result = true;
        searchBreak = true;
        break;
      }
    }
    if (!searchBreak) {
      Iterator < Class < ? extends Server >  >  it = serverSet.iterator();
      while (it.hasNext()) {
        Class < ? extends Server >  next = it.next();
        // note: we can't use equalsIgnoreCase here
        if (next.getName().equals(clazz.getName())) {
          result = true;
          searchBreak = true;
          break;
        }
      }
    }
    return result;
  }

  public  < T extends Client >  void registerClient(T clientImpl) {
    doNotAllowNullValue(clientImpl);
    clientSet.add((Class < ? extends Client > ) clientImpl.getClass());
    clients.put(clientImpl.getClass().getName(), clientImpl);
  }

  public void registerServer(Class < ? extends Server >  serverImpl) {
    doNotAllowNullValue(serverImpl);
    serverSet.add(serverImpl);
  }

  private void doNotAllowNullValue(Object toCheck) {
    if (toCheck == null) {
      final String msg = "You can't pass null to this method!";
      throw new NullPointerException(msg);
    }
  }

  private void doNotAllowUnregisteredNullValue(boolean isRegistered) {
    if (!isRegistered) {
      final String msg = "Either the client or the server was not registered in this router. Register it first!";
      throw new IllegalArgumentException(msg);
    }
  }
}

Sample Implementation and Test

Now let's see how a real implementation could looks like and how it works in practise. First of all we are gonna define some responses and requests. Then we will create the clients and servers. Finally we will test it, by running a junit test to show it in action.
//SAMPLE CLIENT RESPONSE
public class ClientResponse implements Response < String >  {
  private String response;
  public String getResponse() {return response;}
  public void setResponse(String value) {response = value;}
}

//SAMPLE SERVER REQUEST
public class ServerRequest implements Request < String >  {
  String request;
  public String getRequest() {return request;}
  public void setRequest(String value) {request = value;}
}

// SAMPLE CLIENT IMPL
public class ClientImpl implements Client {
  public  < T extends Response < ? > > void onServerResponse(T response) {
    System.out.println(response.getResponse());
  }
}

//SAMPLE SERVER IMPL
public class ServerImpl implements Server {
  public < T extends Request < ? > >  void onClientRequest(T request, Client client) {
    // handle request and depending on it create response
    ClientResponse clientResponse = new ClientResponse();
    clientResponse.setResponse("Server is sending a response to client...");
    // route response back to client immediately or whenever you want
    client.onServerResponse(clientResponse);
  }
}

public class RouterTest {
  @Test
  public void testRouter() {
    Router.turnOn().registerClient(new ClientImpl());
    // servers would be only referenced and lazy instantiated later
    Router.turnOn().registerServer(ServerImpl.class);
    System.out.println("Client is sending a request to server...");
    ServerRequest request = new ServerRequest();
    request.setRequest("Client is sending a request to server...");
    Router.turnOn().routeClientToServer(ClientImpl.class, ServerImpl.class, request);
  }
}


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 22, 2014

Programming Design Pattern - Memento Pattern Applied - Best Practise

Hi there!

Today i'm gonna show the Memento design pattern in action. The Memento design pattern is a very useful programming design pattern whenever you need to perform save, undo and restore functions.

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 Memento 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 example

In our example we will see, how we could perform save and undo actions restoring objects from a text file.

The Memento

That's the generic interface you could use while dealing with memento's capabilities. We will implement the memento on the fly in the Originator bellow. In other words, as soon as we need it in line.

// 1 STEP: DEFINE THE MEMENTO 
public interface Memento < T > {
    T getMemento();
    void setMemento(T state);
}

The Originator

That's the generic interface we will use to implement the Originator. I will create it also on the fly in the client. In a few seconds bellow. :)

//2 STEP: DEFINE THE ORIGINATOR 
public interface Save < T > extends Memento < T > {
    Memento < T > save();
    void restore(Memento < T > memento);
}

The Interface Undo

That's the generic interface we will use to create the care taker. I will create it also on the fly in the client. Be patient. :)

//3 STEP: DEFINE THE CARETAKER
public interface Undo < T > {
    public void addMemento(Memento < T > state) ;
    public Memento < T > getMemento(int index);
}

The concrete CareTaker

That's the abstract implementation of the generic interface. I will create it also on the fly in the client. Stay tuned. :)

//4 STEP: IMPLEMENT A ABSTRACTCARATAKER
public abstract class UndoCareTaker < T > implements Undo < T > {
    private List < Memento < T > > mementoList = new ArrayList < Memento < T > > ();
    public void addMemento(Memento < T > state) {
        if (state != null) {
            mementoList.add(state);
        }
    }
    public Memento < T > getMemento(int index) {
        int min = 0;
        int max = mementoList.size()-1;
        if(mementoList.isEmpty()){
            String msg = "CareTaker has no entry! Passed index:";
            throw new IndexOutOfBoundsException(msg + index);
        }
        if(!(index > = min && index < = max)){
            String msg = "Passed index:"+index+" > Allowed index range: ";
            throw new IndexOutOfBoundsException(msg + min + " - " + max);
        }
        return mementoList.get(index);
    }
}

The Originator Ifself

That's the abstract implementation of the interface generic interface Save.

//5 STEP: IMPLEMENT A ABSTRACTORIGINATOR
public abstract class SaveOriginator < T > implements Save < T >{
    private T state;
    public void setMemento(T state) {this.state = state;}
    public T getMemento() {return state;}
    public void restore(Memento < T > memento) {setMemento(memento.getMemento());}
    public Memento < T > save() {
        Memento < T > memento = new Memento < T > () { // created on the fly as i promissed! :)
            private T state;
            @Override
            public void setMemento(T state) {this.state = state;}
            @Override
            public T getMemento() {return state;}
        };
        memento.setMemento(state);
        return memento;
    }
}

The Test

Finally, let's see how it works in practise.

public class Client {
    public static void main(String[] args) {
        Save < String > originator = new SaveOriginator < String > (){};//created on the fly
        Undo < String > careTaker = new UndoCareTaker < String > (){};//created on the fly
        originator.setMemento("State #1");
        originator.setMemento("State #2");
        careTaker.addMemento(originator.save());
        originator.setMemento("State #3");
        careTaker.addMemento(originator.save());
        originator.setMemento("State #4");
        System.out.println("Current State: " + originator.getMemento());
        originator.restore(careTaker.getMemento(0));
        System.out.println("First saved State: " + originator.getMemento());
        originator.restore(careTaker.getMemento(1));
        System.out.println("Second saved State: " + originator.getMemento());
    }
}

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 - Observer Pattern Applied - Best Practise

Hi there!

Today i'm gonna show the Observer design pattern in action. The Observer design pattern is a very useful programming design pattern whenever you need to notify classes or objects depending on changes or on user interactions. This is one of the most used pattern i think.

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 Observer 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 example

In our example we will see, how we could notify all postmans every time new posts arrives in the post office central station.

Observer and Observable

Those interfaces are part of the default java library. For that reason we will not invent the wheel again. We will just use it.

The PostOffice Observable

This will be our observable. In other words, the object which holds a register method for observers interested in being notified, as soon as changes in the post office occurs.

import java.util.Observable;
public class PostOffice extends Observable {
    public void receberCartas(){
        System.out.println("New post arrived!");
        setChanged();
    }
    public void distributePost(){
        notifyObservers();
    }
}

The Postman Observer

This is the observer itself interested in being notified, as soon as changes in the post office occurs.

import java.util.Observable;
import java.util.Observer;
public class Postman implements Observer {
    @Override
    public void update(Observable o, Object arg) {
        System.out.println("Postman: distributing posts...");
    }
}

The Test

Let's see how those classes interacts together. Pay close attention, because this pattern will surely be one of the most used in your programming life! ;)

public class Client {
    public static void main(String[] args) {
        PostOffice postoffice =  new PostOffice();
        // adding postmans to the post office (observers)
        postoffice.addObserver(new Postman());
        // Simulating arrival of letters in the central post office
        postoffice.receberCartas();
        // simulating postmans distributing letters
        postoffice.distributePost();
    }
}

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 - Adapter Pattern Applied - Best Practise

Hi there!

Today i'm gonna show the Adapter design pattern in action. The Adapter design pattern is a very useful programming design pattern whenever you need to ensure communication between incompatible interfaces, classes or objects.

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 Adapter 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 example

In our example we will see, how we could adapt incompatible interfaces so that they can interact together. We will connect a  rounded 3-pins plug with a rectangular 2-pins plug.

Incompatible Classes

The classes to adapt.

public class CylinderSocket {
    public CylinderPin cylinderPin;
    
    public CylinderSocket(){
        this.cylinderPin=new CylinderPin("corrent", "neutro", "terra");
    }
}
public class RectangularPlug {//ADAPTEE
    public String corrente;
    public String neutro;

    public String getPower() {
        return "power on!";
    }
}

The Adapter

To be able to adapt something, first of all we must define the common interface between at least two classes/objects.

public interface Plugable { // "TARGET" INTERFACE
    public String getPower();
}

The Test

Finally, let's test our adapter which will connect a rounded plug with a rectangular plug.

public class Client {
    public static void main(String[] args) {
        // Rounded plug with 3 pins with rectangular plug with 2 pins
        CylinderSocket cylinderSocket = new CylinderSocket();
        // Client knows only the interface
        Plugable plugable = new PlugAdapter(cylinderSocket);
        // see if connection works
        System.out.println(plugable.getPower());
    }
}

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 - Mediator Pattern Applied - Best Practise

Hi there!

Today i'm gonna show the Mediator design pattern in action. The Mediator design pattern is a very useful programming design pattern whenever you want to centralize logics making it maintainable when a lot of objects has to communicate together.

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 Mediator 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 example

In our example we will see, how we could centralize the logic from a bunch of devices in a smart house making it better maintainable and decoupling the objects from each other.

The Events

In our example, we will be dealing with a lot of devices interacting with each other in a smart house. Those devices fire events. Let's define some events for each of them. After that we will define the devices itself.

public enum Evento {
    TERMOMETRO, METEOROLOGIA, LIXO, DISPERTADOR, 
    AGENDA, MAQUINA_CAFE, AR_CONDICIONADO,BORRIFADOR_PLANTAS;
}
public interface Occurrence {
    void ocorrencia(Evento evento, Object origin);
}

The Devices to mediate

In our example, we have a lot of devices in our house to mediate. Let's define some.

public abstract class Device{
    private Occurrence occurrence;
    public Device(Occurrence centralControl) {
        this.occurrence = centralControl;
    }
    public void inform(Evento evento) {
        occurrence.ocorrencia(evento, this);
    }
    public abstract void update();
}
public class Agenda extends Device{

    public Agenda(Occurrence ocorrencia) {
        super(ocorrencia);
    }
    public void exameMedico(){
        inform(Evento.AGENDA);
    }
    @Override
    public void update() {
        System.out.println("Visitando médico...!");
    }

}
public class ArCondicionado extends Device{
    public ArCondicionado(Occurrence ocorrencia) {
        super(ocorrencia);
    }
    public void fazerManutencao(){
        inform(Evento.AR_CONDICIONADO);
    }
    @Override
    public void update() {
        System.out.println("Manutenção feita com sucesso!");
    }
}
public class BorrifadorPlantas extends Device{
    public BorrifadorPlantas(Occurrence ocorrencia) {
        super(ocorrencia);
    }
    public void faltandoAgua(){
        inform(Evento.BORRIFADOR_PLANTAS);
    }
    @Override
    public void update() {
        System.out.println("Registro aberto. Pode borrifar!");
    }
}
public class Dispertador extends Device {

    public Dispertador(Occurrence ocorrencia) {
        super(ocorrencia);
    }

    public void horaDeTrabalhar() {
        inform(Evento.DISPERTADOR);
    }

    @Override
    public void update() {
        System.out.println("Acorrrrrdaaaaaa! Vai trabalhar menino!!!");
    }
}
public class MaquinaCafe extends Device{

    public MaquinaCafe(Occurrence ocorrencia) {
        super(ocorrencia);
    }
    public void cofreMoedasCheio(){
        inform(Evento.MAQUINA_CAFE);
    }
    @Override
    public void update() {
        System.out.println("Cofre esvaziado! Maquina is ready!");
    }

}
public class Meteorologia extends Device{

    public Meteorologia(Occurrence ocorrencia) {
        super(ocorrencia);
    }
    
    public void alertaDeTempestade(){
        inform(Evento.METEOROLOGIA);
    }
    @Override
    public void update() {
        System.out.println("Fique em casa! Tornado se aproximando!");
    }

}
public class RecolhaLixo extends Device{

    public RecolhaLixo(Occurrence ocorrencia) {
        super(ocorrencia);
    }
    public void colocarLixoPraFora(){
        inform(Evento.LIXO);
    }
    @Override
    public void update() {
        System.out.println("O caminhão de lixo irá passar daqui a pouco!");
    }

}

The Mediator

This class will be mediating between the devices in the house. It is like the CPU in the computer if you like the analogy. It centralizes the logic in one place.

public class CentralControle implements Occurrence {
    @Override
    public void ocorrencia(Evento evento, Object origin) {
        switch (evento) {
        case AGENDA:((Agenda)origin).update();break;
        case AR_CONDICIONADO:
            // FAZER MANUTENÇÃO...
            // ...ATUALIZAR APARELHO
            ((ArCondicionado)origin).update();
            break;
        case BORRIFADOR_PLANTAS:((BorrifadorPlantas)origin).update();break;
        case DISPERTADOR:((Dispertador)origin).update();break;
        case LIXO:((RecolhaLixo)origin).update();break;
        case MAQUINA_CAFE:((MaquinaCafe)origin).update();break;
        case METEOROLOGIA:((Meteorologia)origin).update();break;
        case TERMOMETRO:((Termometro)origin).update();break;
        default:break;}
    }
}

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 - Iterator Pattern Applied - Best Practise

Hi there!

Today i'm gonna show the Iterator design pattern in action. The Iterator design pattern is a very useful programming design pattern whenever you need to iterate over structures without knowing how this structure is implemented.

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 Iterator 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 example

In our example we will see, how we could iterate over a restaurant's menu, showing the food options to our clients.

The Iterable and Iterator

Because those interfaces are part of the java default library, we will not invent the wheel again. So we will make usage of it. You don't need to implement it. I've just inserted here in case you want to understand the details and ideas behind it.

import java.util.Iterator;
public interface Iterable < T > {
    Iterator < T > iterator();
}
public interface Iterator < E > {
    boolean hasNext();
    E next();
    void remove();
}

The Product

Well, the idea behind the iterator is to iterate over a structure without knowing the details about this implementation. We just want to iterate over it to get some information about this structure. For this reason we first need a product (in our case Food) and a structure (in our case the MenuIterator). Note: in the real world we would name it just Menu. But for this tutorial here, I've intentionally defined MenuIterator to facilitate the understanding.

public class Food {
    private String name;
    private String description;
    private boolean vegetarian;
    private double price;
    public Food(String name, String description, boolean vegetarian, double price) {
        super();
        this.name = name;
        this.description = description;
        this.vegetarian = vegetarian;
        this.price = price;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    public boolean isVegetarian() {
        return vegetarian;
    }
    public void setVegetarian(boolean vegetarian) {
        this.vegetarian = vegetarian;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    @Override
    public String toString() {
        return getName()+", "+getPrice()+" R$\n  - "+getDescription();
    }
}
public class MenuIterator implements Iterator < Food > {
    private Food[] foodOptions;
    int position = 0;
    MenuIterator(Food[] foodOptions){this.foodOptions=foodOptions;}
    @Override
    public boolean hasNext() {
        if(position > = foodOptions.length || foodOptions[position]==null){
            return false;
        }return true;
    }
    @Override
    public Food next() {
        final Food food = foodOptions[position];
        position++;
        return food;
    }
    @Override
    public void remove() {/*NOP*/}
}

The Barmaid

Our Barmaid will use the iterator to navigate over the menu showing the food options to the client.

public class Barmaid {
    private Iterable < Food > menu;
    public Barmaid(Menu menu) {
        this.menu = menu;
    }
    public void showMenu(){
        final Iterator < Food > iterator = menu.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next().toString());
        }
    }
}

The Test

Finally, we've opened our restaurant and the barmaid is showing the menu's to the clients. :)

public class Client {
    public static void main(String[] args) {
        String name = "Roast beef";
        String description = "Delicious roast beef argentino";
        boolean vegetarian = false;
        double price = 12.99;
        final Food roastBeef = new Food(name,description,vegetarian, price);
        name = "Sopa tomate";
        description = "Deliciosa sopa de tomate com oregano e creme de leite";
        vegetarian = true;
        price = 8.50;
        final Food sopaTomate = new Food(name,description,vegetarian, price);
        Food[] foodOptions = new Food[]{roastBeef, sopaTomate };
        final Menu menu = new Menu(foodOptions);
        final Barmaid barmaid = new Barmaid(menu);
        barmaid.showMenu();
    }
}

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 - Interpreter Pattern Applied - Best Practise

Hi there!

Today i'm gonna show the Interpreter design pattern in action. The Interpreter design pattern is a very useful programming design pattern while dealing with transformations, language issues, changing from one system to another and so on.

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 Interpreter 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 example

In our example we will see, how we could interpret different number systems like decimal to octal or binary and so on.

The Context of the interpretation

This is one of the core concept of interpretation. It must define the context. It is in the nature of the thing. Without a context, no interpretation. So let's define our context first. We want to implement a number system interpretation. For this reason I'm defining the types of number system. After that I'm able to define the Interpreter itself and the NumberSystemInterpreter.

public enum InterpreterContext {INTEGER_TO_BIN,INTEGER_TO_HEX,INTEGER_TO_OCTAL;}

public interface Interpreter < T, V > {
    T interpret(V toInterpret, InterpreterContext context);
}

public class NumberSystemInterpreter implements Interpreter < String, Integer > {
    @Override
    public String interpret(Integer toInterpret, InterpreterContext context) {
        switch (context) {
        case INTEGER_TO_BIN:
            return Integer.toBinaryString(toInterpret);
        case INTEGER_TO_HEX:
            return Integer.toHexString(toInterpret);
        case INTEGER_TO_OCTAL:
            return Integer.toOctalString(toInterpret);
        default:return "No grammar available";
        }
    }
}

The Expressions

That's also typical for Interpreter pattern. We need some expressions to be interpreted. In our case we will be defining three Expressions. One for each number system to be interpreted.

public interface Expression < T, V > {
    String interpret(Interpreter < T, V > interpreter);
}
public class OctalExpression implements Expression < String, Integer > {
    private int toInterpret;
    public OctalExpression(int integer){this.toInterpret=integer;}
    @Override
    public String interpret(Interpreter < String, Integer > numberSystem) {
        return numberSystem.interpret(toInterpret, InterpreterContext.INTEGER_TO_OCTAL);
    }
}
public class HexExpression implements Expression < String, Integer > {
    private int toInterpret;
    public HexExpression(int integer){this.toInterpret=integer;}
    @Override
    public String interpret(Interpreter < String, Integer > numberSystem) {
        return numberSystem.interpret(toInterpret, InterpreterContext.INTEGER_TO_HEX);
    }
}
public class BinaryExpression implements Expression < String, Integer > {
    private int toInterpret;
    public BinaryExpression(int integer){
        this.toInterpret=integer;
    }
    @Override
    public String interpret(Interpreter < String, Integer > interpreter) {
        return interpreter.interpret(toInterpret, InterpreterContext.INTEGER_TO_BIN);
    }
}

The Test

Finally, let's see the interpreter in action. ;)

public class Client {
    public static void main(String[] args) {
        Interpreter < String, Integer > numberSystem = new NumberSystemInterpreter();
        Expression < String, Integer > decimalToBin = new BinaryExpression(23);
        System.out.println(decimalToBin.interpret(numberSystem));
        Expression < String, Integer > decimalToHex = new HexExpression(23);
        System.out.println(decimalToHex.interpret(numberSystem));
        Expression < String, Integer > decimalToOctal = new OctalExpression(23);
        System.out.println(decimalToOctal.interpret(numberSystem));
    }
}

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

Wednesday, August 20, 2014

Programming Design Pattern - Bridge Pattern Applied - Best Practise

Hi there!

Today i'm gonna show the Bridge design pattern in action. The Bridge design pattern is a very useful programming design pattern whenever you need to be able to vary abstractions and implementations of structures.

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 Bridge 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 example

In our example we will see, how we could separete the remote control from the TV, so we can vary both sides. (The abstraction[remote controls] and the implemention[TV's] of it) This way we will be able to implement platforms dependent TV's and remote controls.

The Bridge

This is the common interface that acts between two object structures (the bridge). The TV types are the structure of different clients that can have different remote controls.

public interface TV {
    public void on();
    public void off();
    public void setChannel(int id);
}
public class Sony implements TV {
    public void on() {System.out.println("Sony TV on!");}
    public void off() {System.out.println("Sony TV off!");}
    public void setChannel(int id){System.out.println("Sony Channel set: "+id);}
}
public class Philips implements TV {
    private int channelId=0;//SPECIFIC FEATURE FROM PHILIPS
    public void on() {System.out.println("Philips TV on!");}
    public void off() {System.out.println("Philips TV off!");}
    public void setChannel(int id){
        this.channelId=id;
        System.out.println("Philips Channel set: "+id);
    }
    // SPECIFIC IMPLEMENTATION FROM PHILIPS
    public int getChannelId() {return channelId;}
}

The Remote Control

Each TV communicates over different remote controls and each of them could have more, less or different functions.

public abstract class ControleRemoto {
    protected TV tv;
    public ControleRemoto(TV tv) {this.tv = tv;}
    public abstract void on();
    public abstract void off();
    public abstract void setChannel(int id);
}
public class PhilipsControleRemoto extends ControleRemoto {
    public PhilipsControleRemoto(TV tv) {super(tv);}
    public void on() {tv.on();}
    public void off() {tv.off();}
    public void setChannel(int id) {tv.setChannel(id);}
    // SPECIFIC IMPLEMENTATION FOR PHILIPS
    public void nextChannel(){
        final int currentChannelId = ((Philips)tv).getChannelId();
        tv.setChannel(currentChannelId+1);
    }
}
public class SonyControleRemoto extends ControleRemoto {
    public SonyControleRemoto(TV tv) {super(tv);}
    public void on() {tv.on();}
    public void off() {tv.off();}
    public void setChannel(int id) {tv.setChannel(id);}
}

The Test

Here we can see how the clients (TV's) communicate over the bridges with the different remote controls. With this concept, both, TV's and Remote Control's, can vary.

public class Client {
    public static void main(String[] args) {
        final ControleRemoto philips = new PhilipsControleRemoto(new Philips());
        final ControleRemoto sony = new SonyControleRemoto(new Sony());
        sony.setChannel(3);
        // PHILIPS HAS MORE FUNCTIONALITIES
        philips.setChannel(18);
        ((PhilipsControleRemoto)philips).nextChannel();
    }
}

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 - Chain of Responsibility Pattern Applied - Best Practise


Hi there!

Today i'm gonna show the Chain of Responsibility design pattern in action. The Chain of Responsibility design pattern is a very useful programming design pattern while dealing processes that happens in sequences.

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 Chain of Responsibility 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 example

In our example we will see, how we could implement a customer after sales feedback robot. How could we do it? In this example we will see it.

The abstract chain

This is the base class to be implemented by all participants of this chain.

public abstract class Inspector < T > {
    protected T toInspect;
    protected Inspector < T > next;
    public Inspector(Inspector < T > next) {this.next = next;}
    public void inspect(T toInspect){
        this.toInspect=toInspect;
        if(toInspect==responsibility()){
          System.out.println(responsibility() + " " + action());
        }toNextInspector();
    }
    public abstract T responsibility();
    public abstract T action();
    public void toNextInspector(){
        if(next instanceof NullObject){return;}
        next.inspect(toInspect);
    }
    public static class NullObject extends Inspector < String > {
        public NullObject() {super(null);}
        public String responsibility() {return null;}
        public String action() {return null;}
    }
}

The participants of the chain

Every participant has a single responsibility and gets a chance to process it. If it can not handle it, it will pass it over to the next till the end.

public class Complaint extends Inspector < String > {
    public Complaint(Inspector < String > next) {super(next);}
    public String responsibility() {return "Reclamação";}
    public String action() {return "Enviar pro departamento de qualidade!";}
}
public class Billing extends Inspector < String > {
    public Billing(Inspector < String > next) {super(next);}
    public String responsibility() {return "Cobrança";}
    public String action() {return "Enviar pro departamento de pos-vendas!";}
}
public class Praise extends Inspector < String > {
    public Praise(Inspector < String > next) {super(next);}
    public String responsibility() {return "Elogio";}
    public String action() {return "Enviar pro RH!";}
}
public class Suggestion extends Inspector < String > {
    public Suggestion(Inspector < String > next) {super(next);}
    public String responsibility() {return "Sugestão";}
    public String action() {return "Enviar para o setor de desenvolvimento!";}
}
public class Spam extends Inspector < String > {
    public Spam(Inspector < String > next) {super(next);}
    public String responsibility() {return "Spam";}
    public String action() {return "Jogar no lixo!";}
}

The Test

Finally, let´s see how our customer after sales robot works. :)

public class Client {
    public static void main(String[] args) {
        Inspector < String > inspector;
        String[] incomingPost = new String[] { 
                "ABC", 
                "Spam", 
                "Elogio", 
                "Reclamação", 
                "Sugestão",
                "Cobrança" };
        for (String post : incomingPost) {
            inspector = new Spam(new Complaint(new Praise(new Billing(new Suggestion(new Inspector.NullObject())))));
            inspector.inspect(post);
        }
    }
}

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 - Composite Pattern Applied - Best Practise

Hi there!

Today i'm gonna show the Composite design pattern in action. The Composite design pattern is a very useful programming design pattern while dealing with trees, folders and structures.

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 Composite 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 example

In our example we will see, how we could implement a menu structure for a restaurant. How could we do it? In this example we will see it.

The Menu Component

That's the base class for all menu itens (topics) and sub-itens (menu itself)

public abstract class MenuComponent {
    // MAKE INTERFACE FROM FOOD
    public String getName(){throw new UnsupportedOperationException();}
    public void setName(String name){throw new UnsupportedOperationException();}
    public String getDescription(){throw new UnsupportedOperationException();}
    public void setDescription(String description){throw new UnsupportedOperationException();}
    public boolean isVegetarian(){throw new UnsupportedOperationException();}
    public void setVegetarian(boolean vegetarian){throw new UnsupportedOperationException();}
    public double getPrice(){throw new UnsupportedOperationException();}
    public void setPrice(double price){throw new UnsupportedOperationException();}
    public void showMenu(){throw new UnsupportedOperationException();}
    // COMPOSITE METHODS
    public void add(MenuComponent component){throw new UnsupportedOperationException();}
    public void remove(MenuComponent component){throw new UnsupportedOperationException();}
    public MenuComponent getChild(int index){throw new UnsupportedOperationException();}
}

The Menu itens

Well, let´s implement the base item we wanna offer in our restaurant. (Food)

public class Food extends MenuComponent{
    private String name;
    private String description;
    private boolean vegetarian;
    private double price;
    public Food(String name, String description, boolean vegetarian, double price) {
        super();
        this.name = name;
        this.description = description;
        this.vegetarian = vegetarian;
        this.price = price;
    }
    public String getName() {return name;}
    public void setName(String name) {this.name = name;}
    public String getDescription() {return description;}
    public void setDescription(String description) {this.description = description;}
    public boolean isVegetarian() {return vegetarian;}
    public void setVegetarian(boolean vegetarian) {this.vegetarian = vegetarian;}
    public double getPrice() {return price;}
    public void setPrice(double price) { this.price = price;}
    public void showMenu() {System.out.println(toString());}
    @Override
    public String toString() {
        return getName()+", R$"+getPrice()+" - vegetário: "+isVegetarian()+"\n  - "+getDescription();
    }
}

The Menu ifself

Well, if we want to present the restaurant's specialties, we must define the menu itself. This happens here.

public class Menu extends MenuComponent {
    private List < MenuComponent > tree =  new ArrayList < MenuComponent > ( );
    private String name, description;
    public Menu(String name, String description) {
        this.name = name; this.description = description;
    }
    public String getName() {return name;}
    public String getDescription() {return description;}
    public void showMenu() {
        System.out.println(getName());
        System.out.println(getDescription());
        System.out.println("--------------------");
        final Iterator iterator = tree.iterator();
        while(iterator.hasNext()){
            iterator.next().showMenu();
        }
    }
    public void add(MenuComponent component) {tree.add(component);}
    public void remove(MenuComponent component) {tree.remove(component);}
    public MenuComponent getChild(int index) {return tree.get(index);}
}

The Barmaid

Also need someone that that receives the orders from the customers. So let´s define it.

public class Barmaid {
    private MenuComponent menus;
    public Barmaid(MenuComponent menus) {
        this.menus = menus;
    }
    public void showMenus(){
        menus.showMenu();
    }
}

The Test

Finally, let´s test our brand new restaurant´s menu and see how it works in practise.

public class Client {
    public static void main(String[] args) {
        MenuComponent meatMenu = new Menu("Carnes", "Cardapio de carnes nobres");
        MenuComponent soupMenu = new Menu("Sopas", "Cardapio de sopas vegetárianas");
        MenuComponent coffeeMenu = new Menu("Cafes", "Cardapio de café");
        MenuComponent allMenusTogether = new Menu("Todos cardapios", "Todas ofertas do nosso restaurante");
        // ADD MENU'S TO THE GENERAL MENU
        allMenusTogether.add(meatMenu);
        allMenusTogether.add(soupMenu);
        allMenusTogether.add(coffeeMenu);
        // ADD FOOD TO THE MEAT MENU
        String name = "Roast beef";
        String description = "Delicious roast beef argentino";
        boolean vegetarian = false;
        double price = 12.99;
        final Food roastBeef = new Food(name,description,vegetarian, price);
        meatMenu.add(roastBeef);
        // ADD FOOD TO THE SOUP MENU
        name = "Sopa tomate";
        description = "Deliciosa sopa de tomate com oregano e creme de leite";
        vegetarian = true;
        price = 8.50;
        final Food tomatoSoup = new Food(name,description,vegetarian, price);
        soupMenu.add(tomatoSoup);
        // ORDER MENU'S FROM BARMAID (BARMAID SHOWS THE AVAILABLE MENU'S)
        final Barmaid barmaid = new Barmaid(allMenusTogether);
        barmaid.showMenus();
    }
}

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 - Facade Pattern Applied - Best Practise

Hi there!

Today i'm gonna show the Facade design pattern in action. The Facade design pattern is a very useful programming design pattern when you are trying to simplify a lot of communication and actions between a bunch of classes or objects.

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 Facade 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 example

In our example we will see, how we could simplify the turn ON and OFF process of a stereo home cinema. Imagine you bought a stereo home cinema. Instead of connecting all your components every time you watch a movie, we will simplify this process by using a facade. 

The components

Typically, the facade coordinates the communication between lots of objects making it simple to use it. For that reason, let´s define a lot of components that communicates together to simulate a situation like that. What we have here are home cinema devices.

public class Light {
    public void on(){System.out.println("light on");}
    public void off(){System.out.println("light off");}
    public void dim(){System.out.println("dimming lights down");}
}
public class WatchScreen {
    public void down(){System.out.println("Sliding screen down");}
    public void high(){System.out.println("Sliding screen high");}
}
public class PopcornMaschine {
    public void on(){System.out.println("popcorn maschine on");}
    public void off(){System.out.println("popcorn maschine off");}
    public void start(){System.out.println("preparing popcorn...");}
}
public class CdPlayer {
    private Amplifier amplifier;
    public void on(){System.out.println("CD Player on!");}
    public void off(){System.out.println("CD Player off!");}
    public void eject(){System.out.println("Eject");}
    public void pause(){System.out.println("Pause");}
    public void play(){System.out.println("play");}
    public void stop(){System.out.println("stop");}
}
public class Tuner {
    private Amplifier amplifier;
    public void on(){System.out.println("Tuner on!");}
    public void off(){System.out.println("Tuner off!");}
    public void setFM(){System.out.println("FM set");}
    public void setAM(){System.out.println("AM set");}
    public void setChannel(double frequency){System.out.println("Channel: "+frequency);}
}
public class DvdPlayer {
    public void on(){System.out.println("DVD Player on!");}
    public void off(){System.out.println("DVD Playerner off!");}
    public void eject(){System.out.println("Eject");}
    public void pause(){System.out.println("Pause");}
    public void play(){System.out.println("play");}
    public void stop(){System.out.println("stop");}
    public void setSurroundSound(){System.out.println("Surround Sound mode");}
    public void setTwoChannelSound(){System.out.println("Two channel sound mode");}
}
public class Amplifier {
    private Tuner tuner;
    private DvdPlayer dvdPlayer;
    private CdPlayer cdPlayer;
    
    public void on(){System.out.println("Amplifier on!");}
    public void off(){System.out.println("Amplifier off!");}
    public void setCD(){System.out.println("setting CD");}
    public void setDVD(){System.out.println("setting DVD");}
    public void setStereoSound(){System.out.println("setting stereo sound");}
    public void setSurroundSound(){System.out.println("settting surround sound");}
    public void setTuner(){System.out.println("setting Tuner");}
    public void setVolume(){System.out.println("setting volume");}
    
}
public class Beamer {
    private DvdPlayer dvdPlayer;
    public void on(){System.out.println("Projetor on");}
    public void off(){System.out.println("Projetor off");}
    public void tvMode(){System.out.println("TV mode");}
    public void wideScreenMode(){System.out.println("Wide screen mode");}
}

The Facade

Instead of switching all devices ON and OFF (in the right sequences) we use the facade. All we have to do now, is to call start and stop watching movie. All needed communication and actions behind the scene will be handled by the facade itself. We don't care about it anymore.

public class HomeCinemaFacade {
    private Amplifier amplifier;
    private Tuner tuner;
    private DvdPlayer dvdPlayer;
    private CdPlayer cdPlayer;
    private Beamer beamer;
    private Light light;
    private PopcornMaschine popcorn;
    private WatchScreen screen;
    
    public HomeCinemaFacade(Amplifier amplifier, Tuner tuner, DvdPlayer dvdPlayer,
            CdPlayer cdPlayer, Beamer beamer, Light light, PopcornMaschine popcorn,
            WatchScreen screen) {
        super();
        this.amplifier = amplifier;
        this.tuner = tuner;
        this.dvdPlayer = dvdPlayer;
        this.cdPlayer = cdPlayer;
        this.beamer = beamer;
        this.light = light;
        this.popcorn = popcorn;
        this.screen = screen;
    }
    
    public void startWatchingMovie(){
        System.out.println("Se prepare! O filme ja vai começar!");
        popcorn.on();
        popcorn.start();
        light.dim();
        screen.down();
        beamer.on();
        beamer.wideScreenMode();
        amplifier.on();
        amplifier.setDVD();
        amplifier.setSurroundSound();
        amplifier.setVolume();
        dvdPlayer.on();
        dvdPlayer.play();
    }
    public void stopWatchingMovie(){
        System.out.println("Desligando Home-Cinema! aguarde...");
        popcorn.off();
        light.on();
        screen.high();
        beamer.off();
        amplifier.off();
        dvdPlayer.pause();
        dvdPlayer.eject();
        dvdPlayer.off();
    }
}

The Test

Finally, let´s watch some movies using our new facade. No more complicated turn ON and OFF processes anymore ;)

public class Client {
    public static void main(String[] args) {
        final HomeCinemaFacade homeCinemaFacade = new HomeCinemaFacade(new Amplifier(),
                new Tuner(), new DvdPlayer(), new CdPlayer(), new Beamer(), new Light(),
                new PopcornMaschine(), new WatchScreen());
        // SIMULATING START OF A MOVIE
        homeCinemaFacade.startWatchingMovie();
    }
}

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