Skip to content

Behavioral Patterns

Template:

Problem:  All implementation details not known until run time.  Implement the known details and let the child implementation classes executed the unknown part determined at run time.

Implement  abstract parent class and let children implement the specific calls required as part of abstract methods impl.

Strategy

Problem:  Interchange different logic into the class as per the need.

Implement multiple algos based on incoming info.

Visitor

Problem: Class hierarchy already existing – and you want to add algo’s doing some data manipulation in these classes – but do not want to add new methods to that family – then use visitor.

Visitor – it’s a way of structuring double dispatch, Also multiple data calculations involved – not just usage of type for visit calls.

In some ways – other than double dispatch – it’s a nice way of removing switch and letting compiler figure which method to call based on the parameter type.

So class implements accept – which takes in the visitor – the visitor call’s its own API – visit that takes in the current object as parameter – so all data is forwarded to that algo. Based on the data type of the current object the call gets executed.

So I will have the following visit existing:

class VisitorTest implements Visitor{

Public void visit(Cat c) { change sound to purr}

Public void visit(Dog d) { bark}

Public void visit(Fish f) { float}

}

Interface Visitor{

Public void visit(Cat c);

Public void visit(Dog d);

Public void visit(Fish f);

}

Class Cat extends Animal{

Public void accept(Visitor v)

{

v.visit(this);

}

}

that C++ didn’t have any form of Run-Time Type Identification (RTTI). They used “double dispatch” to get the target objects to tell them what their type was. But problem above maybe that every time a new class is added to Animal the Visitor implementations + visitor interface – a new method needs to be added. To avoid that you can use generics :

Basically store all visitors for each data type into a map – and every time a new class added put it in the map only.

public interface Visitor<T> {

void visit(T type);

}

public class VisitorRegistry {

private Map<Class<?>, Visitor<?>> visitors = new HashMap<Class<?>, Visitor<?>>();

public <T> void register(Class<T> clazz, Visitor<T> visitor) {

visitors.put(clazz, visitor);

}

public <T> void visit(T thing) {

// needs error checks, and possibly “walk up” to check supertypes if direct type not found

// also — can provide default action to perform – maybe register using Void.class?

@SuppressWarnings(“unchecked”)

Visitor<T> visitor = (Visitor<T>) visitors.get(thing.getClass());

visitor.visit(thing);

}

}

Also – it can be used for recursive operations – along with composite

The Visitor pattern allows you to define new operations on the elements of an object structure without changing the element classes on which they operate. During usage, a Visitor visits each element in the structure via recursive descent (if the elements are contained in a Composite structure), or via iteration (over the elements of a Collection), or via a combination of both (if visited elements are both composed and collected).

Cons

Adding new classes is hard, breaks encapsulation.

Command

Problem: Do not know, and do not want to expose the method to the client. So let the client pass all the info about which method to invoke (Could be another object) to a invoker. The invoker in turn calls the receiver with all the info passed by the client.decouple the requester from the receiver.

Here method info is – creation of an object which wraps internally another object – in which actual call takes place. (Command) . Client passes a concrete command as per need to the invoker. The invoker can also stack the commands – redo, undo or take past actions on all last commands executed.

From outside no other objects really know what actions get performed on what receiver. They just know that if they call the execute() method, their requests will be served.

Cons:explosion of little command classes.

Diff between command / strategy: The Strategy Pattern involves encapsulation of an algorithm, but the Command Pattern effectively encapsulates method invocation.

Chain of Responsibility

processing objects with Command objects – in a series of linked executions.

The fact that you can break the chain at any point differentiates the Chain of Responsibility pattern from the Decorator pattern. Decorators can be thought of as executing all at once without any interaction with the other decorators. Links in a chain can be thought of as executing one at a time, because they each depend on the previous link.
Use the Chain of Responsibility pattern when you can conceptualize your program as a chain made up of links, where each link can either handle a request or pass it up the chain.

Mediator

Problem: Too many objects are interacting and complex interactions are leading to high cost of change of flows.

Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.

You have some number of instances of class X (or maybe even several different types:X, Y & Z), and they wish to communicate with each other (but you don’t want each to have explicit references to each other), so you create a mediator class M. Each instance of X has a reference to a shared instance of M, through which it can communicate with the other instances of X (or X, Y and Z). An observer pattern can help in doing mediating as well …

State

Problem: Behavior changes in class based on the content=state of the class.

Operations have large, multipart conditional statements that depend on the object’s state. The State pattern puts each branch of the conditional in a separate class.

State varies the behavior of some object whose composit two key aspects to consider in working with the state pattern: enumeration and transition. Enumeration simply means identifying the set of possible states (e.g. days of the week), or more abstractly the types of states (i.e. meta states) such as starting, ending, and in between for a workflow engine.Transition means deciding how to model movement between states where this is typically either done by capturing all possible transitions in a tabular representation (i.e. Finite State Machine ) or make each state know its possible “transitions” to other states.ion includes that state.

State pattern implies different classes for each of the different behavior that emerges from a different state. That means if a switch has a power on and off state – then we have two classes. Similarly state = energetic, drained has two different classes : EnergeticState, DrainedState – and the behaviors are different in both.  Conceptually, State is supposed to be stateless, e.g., not hold any data. This is considered as an important “divide and concur” principle of the State pattern: the context holds data and knows how to manipulate it, the state knows when which operation has to be performed.

Interpreter: Specifies how to evaluate sentences in a language. class for each symbol/

Null Object

Problem: Avoid null checks.

Empty implementations provided – so that null checks can be removed. empty methods are in that.

Observer

The observer pattern is used when a class wants to allow other classes to register itself and receive notifications upon events.

Servant

Servant is used for providing some behavior to a group of classes. Instead of defining that behavior in each class – or when we cannot factor out this behavior in the common parent class – it is defined once in the Servant.

No comments yet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: