View
218
Download
0
Category
Preview:
Citation preview
Strategy Intent
Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
Motivation Many algorithms exist for breaking a stream of text into
lines. Hard-coding them in client isn’t desirable since: Clients become more complex Non-used algorithms will be supported Difficult to add new algorithms
We can avoid these problems by encapsulating different line-breaking algorithms in different classes.
Each of these classes are called a strategy.
Strategy – Applicability
Use Strategy pattern whenMany different classes differ only in their
behavior. You need different variants of an algorithm.An algorithm uses data that clients
shouldn’t know about.A class uses multiple conditional
statements.
Strategy – Participants Strategy
Declares an interface to all supported algorithms
ConcreteStrategy Implements the algorithm using the Strategy interface
Context Is configured with a ConcreteStrategy object Maintains a reference to a Strategy object May define an interface that lets the Strategy access
its data.
Strategy Collaborations
Strategy and Context interact to implement the chosen Algorithm. Context may pass all data required to Strategy or alternatively it can pass a reference to itself.
Clients usually create and pass a ConcreteStrategy object to the context, from a family of ConcreteStrategy objects.
Consequences Families of related algorithsm. An alternative to subclassing Context. Strategies eliminate conditional statements. A choice of implementations. Time and space trade-offs. Clients must be aware of different strategies. Communication overhead between Strategy and Context. Increased number of objects. They may be shared.
Strategy – Implentation Issues
Implementation
Defining the Strategy and Context interfaces Context can pass data in parameters to Strategy (better decoupling) Context can pass itself as an argument to Strategy Strategy can keep Context
Strategies as Template parameters In C++ templates can be used to configure a class with a strategy.template<class Iterator> void sort(Iterator _First, Iterator _Last ); template<class Iterator, class Pr> void sort(Iterator _First, Iterator _Last, Pr _Comp );
Making Strategy objects optional
Strategy – Sample Codeimport java.util.* ;class A { public final int i ;
A(int i) { this.i = i ; } }class Ascending implements Comparator {
public int compare(Object o1, Object o2) { A a1=(A)o1, a2=(A)o2 ; if (a1.i<a2.i) return -1 ; if (a1.i>a2.i) return +1 ; return 0 ; }
}class Descending implements Comparator {
public int compare(Object o1, Object o2) { A a1=(A)o1, a2=(A)o2 ; if (a1.i<a2.i) return +1 ; if (a1.i>a2.i) return -1 ; return 0 ; }
}
Strategy – Sample Codepublic class S {
public static void main(String[] args) {A[] asc = { new A(1), new A(5), new A(3), new A(2) } ;A[] dsc = (A[]) asc.clone() ;Arrays.sort(asc,new Ascending()) ;Arrays.sort(dsc,new Descending()) ;System.out.println("Ascending : "+arrStr(asc)) ;System.out.println("Descending: "+arrStr(dsc)) ;
}static String arrStr(A[] a) {
String s = "[" + a[0].i ; for (int i=1;i<a.length;++i)
s += ","+a[i].i ; s+="]" ; return s ;
}}// Output : Ascending : [1,2,3,5]// Descending: [5,3,2,1]
Strategy – Examples class TreeSet
CTOR: TreeSet () : Default comparator. Contained objects must implement Comparable interface
CTOR: TreeSet (Comparator)
class JPanel CTOR: JPanel () : With default layout manager CTOR: JPanel ( LayoutManager )
C++ STL: class maptemplate < class Key, class Type, class Traits = less<Key>, class Allocator=allocator<pair <const Key, Type> > > class map { … }
Observer Intent
Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updates automatically.
Motivation Many UI toolkits separate presentation from application data.
Classes defining presentation and data can be reused independently.
Spreadsheet object and bar-chart object can depict information in the same application data.
They must be notified of any data change. The Observer defines how to establish this relationship between
“Subject” and “Observer”. The interaction is called “Publish-Subscribe”
Observer – Applicability Use Observer pattern when
An abstraction has two aspects, one dependent on the other and encapsulating these aspects in different objects lets you vary and reuse them independently.
A change in an object requires changes on others and you don’t know how many objects to be changed.
An object should be able to notify others without knowing them.
Observer – Participants Subject
Knows its observers. Observer
Defines an updating interface for objects that should be notified of changes in a subject.
ConcreteObject Stores state of interest to ConcreteObserver objects. Sends a notification to its Observers when its state changes.
ConcreteObserver Maintains a reference to ConcreteSubject Store state that should be consistent with the subject’s. Implements the Observer updating interface to keep its state
consistent.
Observer Collaborations
ConcreteSubject notifies its observers whenever a change occurs that could make its observers' state inconsistent with its own
After being informed of a change in the concrete subject, a ConcreteObserver object may query the subject for information.
Observer
Consequences
Abstract coupling between Subject and Observer
Support for broadcast communication
Unexpected updates
Observer – Implementation Mapping subjects to their observers Observing more then one subject Who triggers the update?
Subject Client
Dangling references to deleted Subjects. Making sure Subject state is self-consistent. Avoiding observer-specific update protocols.
Push model Pull model
Specifying modifications of interest explicitly.
Recommended