Presentation is loading. Please wait.

Presentation is loading. Please wait.

02 - Behavioral Design Patterns – 2 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Similar presentations


Presentation on theme: "02 - Behavioral Design Patterns – 2 Moshe Fresko Bar-Ilan University תשס"ח 2008."— Presentation transcript:

1 02 - Behavioral Design Patterns – 2 Moshe Fresko Bar-Ilan University תשס"ח 2008

2 Strategy Moshe Fresko Bar-Ilan University תשס"ו - 2005-2006 Design Patterns Course

3 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.

4 Strategy - Motivation

5 Strategy – Applicability Use Strategy pattern when Many 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.

6 Strategy – General Structure

7 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.

8 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.

9 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 void sort(Iterator _First, Iterator _Last ); template void sort(Iterator _First, Iterator _Last, Pr _Comp ); Making Strategy objects optional

10 Strategy – Sample Code import 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 ; } }

11 Strategy – Sample Code public 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]

12 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 map template < class Key, class Type, class Traits = less, class Allocator=allocator > > class map { … }

13 Observer Moshe Fresko Bar-Ilan University תשס"ו - 2005-2006 Design Patterns Course

14 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”

15 Observer - Motivation

16 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.

17 Observer – General Structure

18 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.

19 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.

20 Observer Consequences Abstract coupling between Subject and Observer Support for broadcast communication Unexpected updates

21 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.


Download ppt "02 - Behavioral Design Patterns – 2 Moshe Fresko Bar-Ilan University תשס"ח 2008."

Similar presentations


Ads by Google