28
Behavioral Patterns Behavioral patterns are patterns whose purpose is to facilitate the work of algorithmic calculations and communication between classes. They use inheritance to control code flow. They define and produce process and run- time flow and identify hierarchies of classes and when and where they become instantiated in code. Some define class instance Some hand off work from one class to another, and Some provide placeholders for other functionality.

Behavioral Patterns Behavioral patterns are patterns whose purpose is to facilitate the work of algorithmic calculations and communication between classes

Embed Size (px)

Citation preview

Page 1: Behavioral Patterns  Behavioral patterns are patterns whose purpose is to facilitate the work of algorithmic calculations and communication between classes

Behavioral PatternsBehavioral patterns are patterns whose purpose is

to facilitate the work of algorithmic calculations and communication between classes.

They use inheritance to control code flow. They define and produce process and run-time flow

and identify hierarchies of classes and when and where they become instantiated in code.Some define class instance Some hand off work from one class to another, and Some provide placeholders for other functionality.

Page 2: Behavioral Patterns  Behavioral patterns are patterns whose purpose is to facilitate the work of algorithmic calculations and communication between classes

Behavioral Patterns

Command pattern

Interpreter

Iterator pattern

Memento pattern

Observer pattern

Strategy pattern

Visitor pattern

Page 3: Behavioral Patterns  Behavioral patterns are patterns whose purpose is to facilitate the work of algorithmic calculations and communication between classes

Command PatternAn object that contains a symbol, name or key

that represents a list of commands, actions or keystrokes.

This is the definition of a macroThe Macro represents a command that is built

from the reunion of a set of other commands, in a given order.

Just as a macro, the Command design pattern encapsulates commands (method calls) in objects allowing us to issue requests without knowing the requested operation or the requesting object.

Page 4: Behavioral Patterns  Behavioral patterns are patterns whose purpose is to facilitate the work of algorithmic calculations and communication between classes
Page 5: Behavioral Patterns  Behavioral patterns are patterns whose purpose is to facilitate the work of algorithmic calculations and communication between classes

Command Pattern Command pattern allows requests to an object to exist as

objects. What does that mean? It means that if you send a request for some function to an

object, the command object can house that request inside the object.

This is useful in the case of undoing or redoing some action, or simply storing an action in a request queue on an object.

When you send the request, it is stored in the object. if you need to access that same request or apply the request or some method on the request to an object, you can use the request object instead of calling the object’s method directly.

Page 6: Behavioral Patterns  Behavioral patterns are patterns whose purpose is to facilitate the work of algorithmic calculations and communication between classes

Command Pattern

The Command pattern has three main components: The invoker component acts as a link between the commands and the receiver houses the receiver and the individual commands as they are sent. The command is an object that encapsulates a request to the receiver. The receiver is the component that is acted upon by each request.

Page 7: Behavioral Patterns  Behavioral patterns are patterns whose purpose is to facilitate the work of algorithmic calculations and communication between classes

Command Pattern

Command design pattern provides the options to queue commands, undo/redo actions other manipulations.Intent

encapsulate a request in an object allows the parameterization of clients with different

requests allows saving the requests in a queue

Page 8: Behavioral Patterns  Behavioral patterns are patterns whose purpose is to facilitate the work of algorithmic calculations and communication between classes

ImplementationThe implementation of the Command design pattern is quite simpleCommand - declares an interface for executing an

operation ConcreteCommand - extends the Command interface,

implementing the Execute method by invoking the corresponding operations on Receiver. It defines a link between the Receiver and the action.

Client - creates a ConcreteCommand object and sets its receiver;

Invoker - asks the command to carry out the request;Receiver - knows how to perform the operations;

Page 9: Behavioral Patterns  Behavioral patterns are patterns whose purpose is to facilitate the work of algorithmic calculations and communication between classes

Implementation steps

The Client asks for a command to be executed.The Invoker takes the command

encapsulates it places it in a queue, and

The Concrete Command that is in charge of the requested command, sending its result to the Receiver.

Page 10: Behavioral Patterns  Behavioral patterns are patterns whose purpose is to facilitate the work of algorithmic calculations and communication between classes

Placing Orders for Buying and Selling Stockspublic interface Order { public abstract void execute ( );}

// Receiver class.class StockTrade { public void buy() { System.out.println("You want to buy stocks"); } public void sell() { System.out.println("You want to sell stocks "); }}

Page 11: Behavioral Patterns  Behavioral patterns are patterns whose purpose is to facilitate the work of algorithmic calculations and communication between classes

// Invoker.class Agent { private m_ordersQueue = new ArrayList();

public Agent() { } void placeOrder(Order order) { ordersQueue.addLast(order); order.execute(ordersQueue.getFirstAndRemove()); } }

Page 12: Behavioral Patterns  Behavioral patterns are patterns whose purpose is to facilitate the work of algorithmic calculations and communication between classes

//ConcreteCommand Class.class BuyStockOrder implements Order { private StockTrade stock; public BuyStockOrder ( StockTrade st) { stock = st; } public void execute( ) { stock . buy( ); }}

Page 13: Behavioral Patterns  Behavioral patterns are patterns whose purpose is to facilitate the work of algorithmic calculations and communication between classes

//ConcreteCommand Class.class SellStockOrder implements Order { private StockTrade stock; public SellStockOrder ( StockTrade st) { stock = st; } public void execute( ) { stock . sell( ); }}

Page 14: Behavioral Patterns  Behavioral patterns are patterns whose purpose is to facilitate the work of algorithmic calculations and communication between classes

// Clientpublic class Client { public static void main(String[] args) { StockTrade stock = new StockTrade(); BuyStockOrder bsc = new BuyStockOrder (stock); SellStockOrder ssc = new SellStockOrder (stock); Agent agent = new Agent();

agent.placeOrder(bsc); // Buy Shares agent.placeOrder(ssc); // Sell Shares }}

Page 15: Behavioral Patterns  Behavioral patterns are patterns whose purpose is to facilitate the work of algorithmic calculations and communication between classes

Observer Pattern

This pattern facilitates communication between a parent class and any dependent child classes, allowing changes to the state of the parent class to be sent to the dependent child classes.

We can use this pattern to allow the state changes in a class to be sent to all its dependent classes.

The class relationship is one-to-many between the class and all its dependents.

Page 16: Behavioral Patterns  Behavioral patterns are patterns whose purpose is to facilitate the work of algorithmic calculations and communication between classes

Observer Pattern

The pattern generally consists of two base classes. The first is called the Subject class

this class acts as the notification engine. The Observer classes act as receivers of the

subject notifications. From these two base class types the concrete

implementations for each type are derived: concrete subject and concrete observer.

Page 17: Behavioral Patterns  Behavioral patterns are patterns whose purpose is to facilitate the work of algorithmic calculations and communication between classes

Observer Pattern

we have a stock system which provides data for several types of client.

We want to have a client implemented as a web based applicationwe will later need to add clients for mobile devices, Palm or

Pocket PC, Later the system have a requirement to notify the users

with sms alerts. Now it's simple to see what we need from the

observer pattern we need to separate the subject(stocks server) from it's

observers(client applications) in such a way that adding new observer will be transparent for the server.

Page 18: Behavioral Patterns  Behavioral patterns are patterns whose purpose is to facilitate the work of algorithmic calculations and communication between classes

Observer Pattern

Observer pattern defines a one-to-many dependency between objects

When one object changes state, all its dependents are notified and updated automatically.

Page 19: Behavioral Patterns  Behavioral patterns are patterns whose purpose is to facilitate the work of algorithmic calculations and communication between classes
Page 20: Behavioral Patterns  Behavioral patterns are patterns whose purpose is to facilitate the work of algorithmic calculations and communication between classes

Observer Pattern

Observable - interface or abstract class defining the operations for attaching and de-attaching observers to the client (Subject)

ConcreteObservable - concrete Observable class. It maintain the state of the object and when a change in the state occurs it notifies the attached Observers.

Observer - interface or abstract class defining the operations to be used to notify this object.

ConcreteObserverA, ConcreteObserver2 - concrete Observer implementations.

Page 21: Behavioral Patterns  Behavioral patterns are patterns whose purpose is to facilitate the work of algorithmic calculations and communication between classes

Observer Pattern

The main framework instantiate the ConcreteObservable object. it instantiate and attaches the concrete observers to it using

the methods defined in the Observable interface. Each time the state of the subject it's changing it notifies

all the attached Observers using the methods defined in the Observer interface.

When a new Observer is added to the application, all we need to do is to instantiate it in the main framework and to add attach it to the Observable object.

The classes already created will remain unchanged

Page 22: Behavioral Patterns  Behavioral patterns are patterns whose purpose is to facilitate the work of algorithmic calculations and communication between classes

Observer Pattern ExampleModel View Controller Pattern

The observer pattern is used in the model view controller (MVC) architectural pattern.

In MVC the this pattern is used to decouple the model from the view.

View represents the Observer and the model is the Observable object.

Page 23: Behavioral Patterns  Behavioral patterns are patterns whose purpose is to facilitate the work of algorithmic calculations and communication between classes

Observer Pattern Example

Event management the Observer patterns is extensively used. Swing and .Net are extensively using the Observer

pattern for implementing the events mechanism.

Page 24: Behavioral Patterns  Behavioral patterns are patterns whose purpose is to facilitate the work of algorithmic calculations and communication between classes

Observer Pattern: a News Agency

Page 25: Behavioral Patterns  Behavioral patterns are patterns whose purpose is to facilitate the work of algorithmic calculations and communication between classes

Observer Pattern: a News Agency

A news agency gather news and publish them to different subscribers.

We need to create a framework for and agency to be able to inform immediately when event occurs

The subscribers can receive the news in different ways: Emails, SMS, ...

The solution need to be extensively enough to support new types of subscribers New subscribers may be new communication

technologies

Page 26: Behavioral Patterns  Behavioral patterns are patterns whose purpose is to facilitate the work of algorithmic calculations and communication between classes

Observer Pattern: a News Agency

The agency is represented by an Observable(Subject) class named NewsPublisher.

This one is created as an abstract class because the agency want to create several types of Observable objects

in the beginning only for business news, but after some time sport and political new will be published.

The concrete class is BusinessNewsPublisher.

.

Page 27: Behavioral Patterns  Behavioral patterns are patterns whose purpose is to facilitate the work of algorithmic calculations and communication between classes

Observer Pattern: a News Agency

In the main class a publisher(Observable) is built and a few subscribers(Observers).

The subscribers are subscribed to the publisher and they can be unsubscribed. new types of subscribers can be easily

added(instant messaging, ...) new types of publisherscan be easily added

(Weather News, Sport News, ...).

Page 28: Behavioral Patterns  Behavioral patterns are patterns whose purpose is to facilitate the work of algorithmic calculations and communication between classes

Observer Pattern: a News Agency

The observer logic is implemented in NewsPublisher. It keeps a list of all it subscribers and it informs them about

the latest news. The subscribers are represented by some observers

(SMSSubscriber, EmailSubscriber). Both the observers mentioned above are inherited

from the Subscriber. The subscriber is the abstract class which is known to

the publisher. The publisher doesn't know about concrete observers, it

knows only about their abstraction