Wednesday, December 13, 2017

Command Pattern

Definition -
    It provides a generic interface to all the classes which implement it to execute certain commands. This can be treated like the director in the builder pattern.


Scenario -

    Let us take an example of the production line itself, where the client places an order for a vehicle and depending on the order a hatchback or a sedan car is created.
In this case -
1. The interface called order which have an execute funtion to process the request of the client. Note, we can name the function with any name, for the sake of understanding it has named as execute.

 
package CommandPattern;

public interface order {
    
    public void execute();

}

2. hatchback is a class which will implement order and create a hatchback.
 
package CommandPattern;

public class hatchback implements order {

    @Override
    public void execute() {
        
        System.out.println("Creating a hatchback");
        
    }

}

3. sedan is a class which will implement order and create a sedan.
package CommandPattern;

public class sedan implements order {

    @Override
    public void execute() {
        
        System.out.println("Creating a sedan");
        
    }

}

4. A class called router which will hold the order object and invokes the method.
package CommandPattern;

public class router {
    
    String typeofcar=null;
    order o=null;
    
    
    
    public void createcar(String type) {
        if(type.equalsIgnoreCase("Hatchback")) {
            o=new hatchback();
        }else if(type.equalsIgnoreCase("Sedan")) {
            o=new sedan();
        }
        
        o.execute();
    }
    
}

5. Client class which will order for a hatchback or a sedan.
   
package CommandPattern;

public class commandpattern {
    
    public static void main(String args[]) {
        
        router r=new router();
        r.createcar("Hatchback");
        r.createcar("Sedan");
        
        
    }

}




Place to use -
1) When you want the client and the implmentor to be independent of each other.
2) When the request processor need not be known to the client during compile time.
3) One interface to do varying operations based on varying commands at varying time.

Place not to use -
1) Can create maintainence nightmare because if the system has lot of commands then it can cause confusions.
2) If the command parameters vary in future then it can cause change in the entire implementation.

The link for the code above is in the link here

No comments:

Post a Comment