Upload
daniella-winifred-parker
View
224
Download
2
Embed Size (px)
Citation preview
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.
Behavioral Patterns
Command pattern
Interpreter
Iterator pattern
Memento pattern
Observer pattern
Strategy pattern
Visitor pattern
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.
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.
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.
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
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;
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.
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 "); }}
// Invoker.class Agent { private m_ordersQueue = new ArrayList();
public Agent() { } void placeOrder(Order order) { ordersQueue.addLast(order); order.execute(ordersQueue.getFirstAndRemove()); } }
//ConcreteCommand Class.class BuyStockOrder implements Order { private StockTrade stock; public BuyStockOrder ( StockTrade st) { stock = st; } public void execute( ) { stock . buy( ); }}
//ConcreteCommand Class.class SellStockOrder implements Order { private StockTrade stock; public SellStockOrder ( StockTrade st) { stock = st; } public void execute( ) { stock . sell( ); }}
// 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 }}
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.
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.
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.
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.
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.
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
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.
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.
Observer Pattern: a News Agency
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
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.
.
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, ...).
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