Download presentation
Presentation is loading. Please wait.
Published byElijah Gibson Modified over 9 years ago
1
The Strategy Pattern (Behavioral) ©SoftMoore ConsultingSlide 1
2
Strategy in the Real World There are many modes of transportation to and from an airport: –personal vehicle– taxi –limousine– bus Choosing a particular transportation “strategy” involves making tradeoffs between cost, time, and convenience. ©SoftMoore ConsultingSlide 2
3
The Strategy Pattern: Basic Idea Strategy provides a set of interchangeable algorithms from which the client chooses. Strategy encapsulates all of the algorithms in separate classes with a common interface. The client picks the strategy of interest. ©SoftMoore ConsultingSlide 3
4
Motivation The selection of an algorithm or policy might depend on information that is available only at run-time. An invoice object for an e-commerce application might need to provide a method for computing sales tax. The algorithm for computing sales tax can differ greatly among states and even within a state. In addition, the approach should be flexible enough so that it can be extended to other countries. We can design a single Invoice class plus multiple SalesTaxStrategy classes. The Invoice object can be configured at run-time with the appropriate SalesTaxStrategy object. ©SoftMoore ConsultingSlide 4
5
Motivation (continued) public abstract class SalesTaxStrategy { public static SalesTaxStrategy getSalesTaxStrategy(OrderInfo orderInfo) {... } abstract public Money getSalesTax(); } class SCSalesTaxStrategy extends SalesTaxStrategy { public Money getSalesTax() {... // compute sales tax for South Carolina } ©SoftMoore ConsultingSlide 5 Note: Factory Method
6
Motivation (continued) public class Invoice { private List lineItems; private SalesTaxStrategy strategy; public Invoice(List lineItems, SalesTaxStrategy strategy) { this.lineItems = lineItems; this.strategy = strategy; } ©SoftMoore ConsultingSlide 6 (continued on next page)
7
Motivation (continued) public Money getTotal() { Money total = new Money(0); for (LineItem item : lineItems) total = total.add(item.getCount() * item.getCost(); total = total.add(strategy.getSalesTax()); } ©SoftMoore ConsultingSlide 7
8
Strategy versus Decorator The Strategy pattern changes the “guts” of an object. –create component object –add strategy to component (component knows about its strategy) –client uses the component The Decorator pattern changes the “skin” of an object. –create component object –create decorator and add component to decorator (component does not know about its decorator) –client uses the decorator ©SoftMoore ConsultingSlide 8 : Client: Component: Strategy : Client: Decorator: Component
9
Strategy Pattern Intent: Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it. Also Known As: Policy Slide 9©SoftMoore Consulting
10
Strategy Pattern (continued) Applicability: Use the Strategy pattern when you want to provide a way to configure a class with one of many behaviors. you need different variants of an algorithm; e.g., algorithms reflecting time/space tradeoffs. an algorithm uses data that clients shouldn’t know about. Use Strategy to avoid exposing complex, algorithm- specific data structures. a class defines many behaviors, and these appear as multiple conditional statements in its operations. Move the conditional branches into their own Strategy class. ©SoftMoore ConsultingSlide 10
11
Strategy Pattern (continued) ©SoftMoore ConsultingSlide 11 Context Strategy algorithm() ConcreteStrategyB algorithm() Structure ConcreteStrategyC algorithm() ConcreteStrategyA algorithm() Client
12
Strategy Pattern (continued) Participants Strategy –declares an interface common to all algorithms. Context uses this interface to call the algorithm defined by a ConcreteStrategy. 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 Strategy access its data. ©SoftMoore ConsultingSlide 12
13
Strategy Pattern (continued) Collaborations Strategy and Context interact to implement the chosen algorithm. A context may pass all data required by the algorithm to the strategy when the algorithm is called. Alternatively, the context can pass itself as an argument to Strategy operations, so that the strategy can call back on the context as required. A context forwards requests from its clients to its strategy. Clients usually create and pass a ConcreteStrategy object to the context. Thereafter, clients interact with context exclusively. There is often a family of ConcreteStrategy objects for a client to choose from. ©SoftMoore ConsultingSlide 13
14
Strategy Pattern (continued) Consequences Families of related algorithms. Hierarchies of Strategy classes define a family of algorithms or behaviors for contexts to reuse. An alternative to subclassing. Encapsulating the algorithm in separate Strategy classes lets you vary the algorithm independently of its context, making it easier to switch, understand, and extend. Strategies reduce conditional statements. The Strategy pattern offers an alternative to conditional statements (multiway branching) for selecting desired behavior. ©SoftMoore ConsultingSlide 14
15
Strategy Pattern (continued) Consequences (continued) A choice of implementations. Strategies can provide different implementations of the same behavior. The client can choose among strategies with different time and space tradeoffs. Clients must be aware of different Strategies. The pattern has a potential drawback in that a client must understand how Strategies differ before it can select the appropriate one. Communication overhead between Strategy and Context. It is likely that some ConcreteStrategies won’t use all the information passed to them through the Strategy interface. ©SoftMoore ConsultingSlide 15
16
Strategy Pattern (continued) Implementation Defining the Strategy and Context interfaces. The Strategy and Context interfaces must give a ConcreteStrategy sufficient access to any data it needs from a context, and vice-versa. Possible approaches include –have Context pass data in parameters to Strategy operations. –have Context pass a reference to itself as a parameter, and let Strategy request data from Context explicitly. ©SoftMoore ConsultingSlide 16
17
Strategy Pattern (continued) Implementation (continued) Strategies as generic parameters. Generics (a.k.a., templates in C++) can be used to configure a class with a strategy. This technique is applicable if the Strategy can be selected at compile-time and does not need to be changed at run-time. Making Strategy objects optional. Context checks to see if it has a Strategy object. If there is one, then Context uses it. If not, then Context carries out default behavior. Clients don’t have to deal with Strategy objects at all unless they need to change the default behavior. ©SoftMoore ConsultingSlide 17
18
Strategy Pattern in Java: Layout Java uses the strategy pattern to layout GUI containers. Containers in AWT and Swing have an add() method that allows the programmer to add controls such as widgets and panels to the container’s content pane. How does the add() method know where to place the controls within the content pane? Containers use a layout manager to provide the “strategy” for laying out controls. Containers have a default layout manager. –flow layout for a panel –frames use a border layout ©SoftMoore ConsultingSlide 18
19
Strategy Pattern in Java: Layout (continued) Programmers can set the layout manager for a container. setLayout(new GridLayout(4, 4)); ©SoftMoore ConsultingSlide 19 ContainerLayoutManager BorderLayoutGridLayoutFlowLayout...
20
Strategy Pattern in Java: Checksum Classes CheckedInputStream and CheckedOutputStream in package java.util.zip use the Strategy pattern. Both classes play the role of a Context in this pattern, and interface CheckSum serves as the Strategy class. Two ConcreteStrategy classes are provided, Adler32 and CRC32. Programmers can set the appropriate Checksum strategy in the stream constructor. CheckedInputStream(InputStream in, Checksum cksum) ©SoftMoore ConsultingSlide 20
21
Strategy Pattern in Java: Checksum (continued) ©SoftMoore ConsultingSlide 21 CheckedInputStream «interface» Checksum Adler32CRC32
22
Strategy Pattern in Java: Sorting In package java.util, both the Arrays class and the Collections class have static sort methods that take an optional parameter type Comparator, which is used to compare objects during the sort. A programmer can create different Comparator objects for different ways to sort (e.g., ascending/descending or based on specific properties such as user id, zip code, state, or last name/first name). ©SoftMooreSlide 22
23
Strategy Pattern in Java: Sorting (continued) ©SoftMooreSlide 23 «interface» Comparator Collections sort() Note that some people view this as an example of the Template Method pattern. NameComparatorStateComparator
24
Related Patterns Strategy and Bridge have similar UML diagrams, but they differ in their intent. Strategy is mainly concerned in encapsulating algorithms, whereas Bridge decouples the abstraction from the implementation in order to provide different implementations for the same abstraction. Strategy and State have similar UML diagrams, but they differ in their intent. –A Strategy encapsulates an algorithm, whereas a State encapsulates state information and state-dependent behavior. –Clients often select the appropriate Strategy but not the State. (But Clients can sometimes select the initial state.) –Both State and Strategy are examples of composition with delegation. ©SoftMoore ConsultingSlide 24
25
Related Patterns (continued) Strategy objects often make good flyweights. Template methods use inheritance to vary part of an algorithm. Strategies use delegation to vary the entire algorithm. A decorator lets you change the “skin” of an object. A strategy lets you change its “guts”. ©SoftMoore ConsultingSlide 25
26
References Strategy method pattern (Wikipedia) http://en.wikipedia.org/wiki/Strategy_pattern Strategy (dofactory) http://www.dofactory.com/Patterns/PatternStrategy.aspx Strategy (Object-Oriented Design) http://www.oodesign.com/strategy-pattern.html Strategy Pattern vs. Case Statement (OO Tips) http://ootips.org/strategy-vs-case.html Strategy for Success (David Geary) http://www.javaworld.com/article/2074195/swing-gui-programming/strategy-for-success.html ©SoftMoore ConsultingSlide 26
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.