Labels

algorithms (22) Design Patterns (20) java (19) linux (14) Snippet (13) service mix (6) soa (4)
Showing posts with label Design Patterns. Show all posts
Showing posts with label Design Patterns. Show all posts

Flyweight


Share objects when they are common some common examples are from the JDK
Integer and String objects
The object is restricted to be created through the factory and the object is shared.
/*

 public static Integer valueOf(int i) {
        assert IntegerCache.high >= 127;
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
*/

Template Method


"Defines the skeleton of the algorithm , and defers some implementation to the sub classes."

the above example makeDrink() calls

  1. addWater
  2. addFruit
  3. addIce
the addFruit implementation is left to the sub classes orange and apple juice makers

the method makeDrink is made final so that the steps of making the juice is not changed

State Design Pattern


"It allows to change the behavior of the object when the state of an object changes"


Memento

Memento

Mediator

mediator

Iterator

  • single responsibility, 
  • simplifies aggregator
  • does not expose implementation of aggregator

Strategy Pattern





  1. Defines a set of algorithms
  2. Makes them interchangeable
  3. clients have the option to select 
in the example below the client can tell the type of indexer to use in the dictionary
the behavior of indexer which changes is moved to another class there by separating
the class which changes and the one which does not change 
the dictionary delegates calls to search and sort to the indexer 

Chain Of Responsibility

CHAIN OF RESPONSIBILITY

Proxy

proxy

Composite

Composite

This Pattern is useful

  1. when there is a need for hierarchical structure
  2. when the leaf and non leaf are to be treated alike 
Example GUI: a text field is the simplest component
a form can be a complex component which can have a field.

Facade

Facade

Adaptor

Adaptor

Builder Pattern


"To create a complex object 
controlled by another class director
Build an object step by step"

Abstract Factory


Provides an interface for creating family of objects
Without knowing concrete classes 

Composition Vs Aggregation

Composition vs Aggregation

 


  1. Composition and Aggregation are almost the same 

  2. composition the contained objects do not exist independently in                                case of the above example the Heart cannot exist without the person.

  3. Aggregation the contained objects can exist independently like 
    Money exists without a person.

Command Design Pattern

The Command Design Patterns main goal is to decouple the invoker from the Receiver.

The invoker is the one which invokes an action on the Receiver, and the receiver is the one on which the command is executed.

CommandPattern

// The Receiver 
package Command;

public class Movie {

public static void start() {
System.out.println("Start Movie");

}

public static void stop() {
System.out.println("Movie Stopped");
}

}






//Play Command
public class PlayMovieCommand implements CommandIntf {

public void execute() {
Movie.start();
}

}

//Stop Command
public class StopMovieCommand implements CommandIntf {

public void execute() {

Movie.stop();
}

}








//The Invoker
package Command;

public class MoviePlayer {
static CommandIntf play;

static CommandIntf stop;

public static void setPlayCmd(CommandIntf playMovCmd) {
play = playMovCmd;
}

public static void setStopCmd(CommandIntf stopMovCmd) {
stop = stopMovCmd;
}

public static void playMovie() {
play.execute();

}

public static void stopMovie() {
stop.execute();
}

}



Singleton Design Pattern

Singleton.jpeg
package singleton;

public class Singleton {
    private static Singleton aSingleton;

    private Singleton() {
    }

    static Singleton getInstance() {
        synchronized (Singleton.class) {
            if (Singleton.aSingleton == null) {
                  Singleton.aSingleton = new Singleton();
            }
        }
        return Singleton.aSingleton;
    }
}


  • only one instance of a class across threads
  • global point of access 








Decorator Design Pattern (Wrapper)

DecoratorPattern.jpeg

DrinkDecorator

public abstract class DrinkDecorator extends Drink {
public Drink drink;

}


Drink


public abstract class Drink { 
    String description;


    int cost;



    abstract int getCost();



    String getDesc() {

        return this.description;


    }


}



Vodka



public class Vodka extends Drink {

    String description = " Vodka ";



    int cost = 100;



    @Override

    int getCost() {


        return this.cost;


    }


}




OrangeJuice & like wise LemonJuice


public class OrangeJuice extends DrinkDecorator {

    String description = " fresh orenge juice ";



    int cost = 5;



    public OrangeJuice(Drink myVodka) {

        this.drink = myVodka;


    }



    @Override

    int getCost() {


        return this.cost + this.drink.getCost();


    }


}



Client Code



//Make Vodka with orange



        //make vodka

        Drink myVodka = new Vodka();


        //mix orenge and vodka


        DrinkDecorator orengeVodka= new OrangeJuice(myVodka);


        //mix lime juie in the orengeVodka


        DrinkDecorator LimeOrengeVodka= new LimeJuice(orengeVodka);


        //the cost of the final vodka should be that of lime


        //orenge and vodka cost


        System.out.println(LimeOrengeVodka.getCost());

Observer Design Pattern

This pattern is used in publisher-consumer kind of situations

Client-id.jpeg

This pattern is used where a change in data which is observable by one or many observers,The pattern is such that no matter what kind of Observers ATMObserver , OnlineAcObsever)  come the Observable or the subject(BankAccount) has no impact.So tomorrow if there is a need to add MobileObserver for BankAccount, that can just be added without any changes and implementing AccountObserver.

The Subject or Observable concrete class,in this case a bank account which is observable.The Observers OnlineACObserver ATMACObserver register with this class and get updates about the bank account.

public class BankAccount implements SubjectObservable {
public ArrayList observers = new ArrayList();

String balance;

String account;

public void deregisterObserver(AccountObserver o) {
observers.remove(observers.indexOf(o));
}

public void notifyObservers() {
for (int i = 0; i < this.observers.size(); i++) {
AccountObserver observer = (AccountObserver) this.observers.get(i);
observer.update("ACCOUNTNUM", "BALANCE < 200");
}
}

public void registerObserver(AccountObserver o) {
observers.add(o);
}

public void setBalance(String balance) {
this.balance = balance;
this.notifyObservers();
}



The Concrete implementation of Observer take the case of ATMACObserver this observer registers with the BankAccount and gets invoked by the Subject when there is a change or update in the Subject.




public class ATMObserver implements AccountObserver {

String message;

SubjectObservable bankAccount;

public ATMObserver(SubjectObservable bankAccount) {
this.bankAccount = bankAccount;
this.bankAccount.registerObserver(this);
}

public void update(String accountNumber, String balance) {
{
this.message = "welcome to ATM " + accountNumber + " " + balance;
}
}





The client code can be as follows.





class Client {
public static void main(String[] args) {
// creating observable Bank Account
SubjectObservable bankAccount = new BankAccount();
// Observer 1 onlin
OnlineAcObserver online = new OnlineAcObserver(bankAccount);
// Observer 2 ATM
ATMObserver atm = new ATMObserver(bankAccount);
//update account values which updates the observer
online.getMessage();


Factory Method Design Pattern

This is one of the Creational Design Pattern,The use of this pattern is to make the classes loosely coupled.
ComputerFactoryIF-id
Client Code which calls creation of computer and who only knows which object to create ,In this case It asks to create an Apple Computer and Give it using ComputerFactoryIF.
Computer aComputer = ComputerFactoryIF.createComputer("apple");
System.out.println(aComputer.getName()); 


The ComputerFactoryIF the interface of all the concrete factories checks as to which type of Computer is to be created and delegates to the appropriate ComputerFactory in this case AppleComputerFac


public class ComputerFactoryIF {

public static Computer createComputer(String string) {
Computer aComp = null;
if (string.equals("apple"))
aComp = AppleComputerFac.createComputer();
else if (string.equals("dell"))
aComp = DellComputerFac.createComputer();
return aComp;
}



There After the corresponding factory creates an instance of the computer and returns(In this case AppleComputer Object).


public class AppleComputerFac extends ComputerFactoryIF {
public static Computer createComputer() {
return new AppleComputer();
}
}



public class AppleComputer extends Computer {
AppleComputer() {
this.name = "AppleComputer";
}
}


 

Search 24 Bytes