Behivioral patterns are specifically concerned with communication between objects.
Chain of responsibility
Chain of responsibility pattern creates a chain of receiver objects for a request. normally each receiver contains reference to another receiver. If one object cannot handle the request then it passes the same to the next receiver and so on.
In this example we have different roles, each having a fixed purchasing limit and a successor. Every time a user in a role receives a purchase request that exceeds his or her limit, the request is passed to his or her successor.
classCheckAuthority{ publicstaticvoidmain(String[] args){ ManagerPPower manager = new ManagerPPower(); DirectorPPower director = new DirectorPPower(); VicePresidentPPower vp = new VicePresidentPPower(); PresidentPPower president = new PresidentPPower(); manager.setSuccessor(director); director.setSuccessor(vp); vp.setSuccessor(president);
// Press Ctrl+C to end. try { while (true) { System.out.println("Enter the amount to check who should approve your expenditure."); System.out.print(">"); double d = Double.parseDouble(new BufferedReader(new InputStreamReader(System.in)).readLine()); manager.processRequest(new PurchaseRequest(d, "General")); } } catch(Exception e) { System.exit(1); } } }
Command Pattern
Command pattern is a behavioral design pattern in which an object is used to encapsulate all information needed to perform an action or trigger an event at a later time. A request is wrapped under an object as command and passed to invoker object. Invoker object looks for the appropriate object which can handle this command and passes the command to the corresponding object which executes the command.
Four terms always associated with the command pattern are command, receiver, invoker and client. A command object knows about receiver and invokes a method of the receiver. Values for parameters of the receiver method are stored in the command. The receiver then does the work. An invoker object knows how to execute a command, and optionally does bookkeeping about the command execution. The invoker does not know anything about a concrete command, it knows only about command interface. Both an invoker object and several command objects are held by a client object. The client decides which commands to execute at which points. To execute a command, it passes the command object to the invoker object.
We have created an interface Order which is acting as a command. We have created a Stock class which acts as a request. We have concrete command classes BuyStock and SellStock implementing Order interface which will do actual command processing. A class Broker is created which acts as an invoker object. It can take and place orders. Broker object uses command pattern to identify which object will execute which command based on the type of command. CommandPatternDemo, our demo class, will use Broker class to demonstrate command pattern.
publicvoidplaceOrders(){ for (Order order : orderList) { order.execute(); } orderList.clear(); } }
publicclassCommandPatternDemo{ publicstaticvoidmain(String[] args){ Stock abcStock = new Stock();
BuyStock buyStockOrder = new BuyStock(abcStock); SellStock sellStockOrder = new SellStock(abcStock);
Broker broker = new Broker(); broker.takeOrder(buyStockOrder); broker.takeOrder(sellStockOrder);
broker.placeOrders(); } }
Interpreter Pattern
Interpreter pattern provides a way to evaluate language grammar or expression. It involves implementing an expression interface which tells to interpret a particular context. Interpreter pattern is used in SQL parsing, symbol processing engine etc.
//Rule: Robert and John are male publicstatic Expression getMaleExpression(){ Expression robert = new TerminalExpression("Robert"); Expression john = new TerminalExpression("John"); returnnew OrExpression(robert, john); }
//Rule: Julie is a married women publicstatic Expression getMarriedWomanExpression(){ Expression julie = new TerminalExpression("Julie"); Expression married = new TerminalExpression("Married"); returnnew AndExpression(julie, married); }
System.out.println("John is male? " + isMale.interpret("John")); System.out.println("Julie is a married women? " + isMarriedWoman.interpret("Married Julie")); } }
Iterator pattern
Iterator pattern is a design pattern in which an iterator is used to traverse a container and access the container’s elements. The iterator pattern decouples algorithms from containers. Iterator pattern is very commonly used in Java and .Net programming environment.
For example, the hypothetical algorithm SearchForElement can be implemented generally using a specified type of iterator rather than implementing it as a container-specific algorithm. This allows SearchForElement to be used on any container that supports the required type of iterator.
publicclassIteratorPatternDemo{ publicstaticvoidmain(String[] args){ NameRepository namesRepository = new NameRepository();
for(Iterator iter = namesRepository.getIterator(); iter.hasNext();){ String name = (String)iter.next(); System.out.println("Name : " + name); } } }
Mediator Pattern
Mediator pattern is used to reduce communication complexity between multiple objects or classes. This pattern provides a mediator class which normally handles all the communications between different classes and supports easy maintenance of the code by loose coupling.
In the following example a mediator object controls the status of three collaborating buttons: for this it contains three methods (book(), view() and search()) that set the status of the buttons. The methods are called by each button upon activation (via the execute() method in each of them). Hence here the collaboration pattern is that each participant (here the buttons) communicates to the mediator its activity and the mediator dispatches the expected behavior to the other participants.
publicstaticvoidmain(String[] args){ new MediatorDemo(); }
}
Memento Pattern
Memento pattern provides the ability to restore an object to its previous state (undo via rollback).
The memento pattern is implemented with three objects: the originator, a caretaker and a memento. The originator is some object that has an internal state. The caretaker is going to do something to the originator, but wants to be able to undo the change. The caretaker first asks the originator for a memento object. Then it does whatever operation (or sequence of operations) it was going to do. To roll back to the state before the operations, it returns the memento object to the originator. The memento object itself is an opaque object (one which the caretaker cannot, or should not, change). When using this pattern, care should be taken if the originator may change other objects or resources - the memento pattern operates on a single object.
Classic examples of the memento pattern include the seed of a pseudorandom number generator (it will always produce the same sequence thereafter when initialized with the seed state)and the state in a finite state machine.
classOriginator{ private String state; // The class could also contain additional data that is not part of the // state saved in the memento.. publicvoidset(String state){ System.out.println("Originator: Setting state to " + state); this.state = state; } public Memento saveToMemento(){ System.out.println("Originator: Saving to Memento."); returnnew Memento(this.state); } publicvoidrestoreFromMemento(Memento memento){ this.state = memento.getSavedState(); System.out.println("Originator: State after restoring from Memento: " + state); } publicstaticclassMemento{ privatefinal String state; publicMemento(String stateToSave){ state = stateToSave; } public String getSavedState(){ return state; } } } classCaretaker{ publicstaticvoidmain(String[] args){ List<Originator.Memento> savedStates = new ArrayList<Originator.Memento>(); Originator originator = new Originator(); originator.set("State1"); originator.set("State2"); savedStates.add(originator.saveToMemento()); originator.set("State3"); // We can request multiple mementos, and choose which one to roll back to. savedStates.add(originator.saveToMemento()); originator.set("State4"); originator.restoreFromMemento(savedStates.get(1)); } }
Observer pattern
Observer pattern is a design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used to implement distributed event handling systems. The Observer pattern is also a key part in the familiar model–view–controller (MVC) architectural pattern.1 The observer pattern is implemented in numerous programming libraries and systems, including almost all GUI toolkits.
The observer pattern can cause memory leaks, known as the lapsed listener problem, because in basic implementation it requires both explicit registration and explicit deregistration, as in the dispose pattern, because the subject holds strong references to the observers, keeping them alive. This can be prevented by the subject holding weak references to the observers.
new HexaObserver(subject); new OctalObserver(subject); new BinaryObserver(subject);
System.out.println("First state change: 15"); subject.setState(15); System.out.println("Second state change: 10"); subject.setState(10); } }
State Pattern
State pattern is used to encapsulate varying behavior for the same object based on its internal state. This can be a cleaner way for an object to change its behavior at runtime without resorting to large monolithic conditional statements and thus improve maintainability.
In Template pattern, an abstract class exposes defined way(s)/template(s) to execute its methods. One or more algorithm steps can be overridden by subclasses to allow differing behaviors while ensuring that the overarching algorithm is still followed. The template method is used in frameworks, where each implements the invariant parts of a domain’s architecture, leaving “placeholders” for customisation options.
Game game = new Cricket(); game.play(); System.out.println(); game = new Football(); game.play(); } }
Visitor Pattern
Visitor pattern is a way of separating an algorithm from an object structure on which it operates. A practical result of this separation is the ability to add new operations to existing object structures without modifying those structures.