1 / 77

Unit 18 Strategy

Unit 18 Strategy. Summary prepared by Kirk Scott. Design Patterns in Java Chapter 23 Strategy. Summary prepared by Kirk Scott. The Introduction Before the Introduction. In general, a single strategy might be thought of as an algorithm or an operation

acton
Download Presentation

Unit 18 Strategy

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Unit 18Strategy Summary prepared by Kirk Scott

  2. Design Patterns in JavaChapter 23Strategy Summary prepared by Kirk Scott

  3. The Introduction Before the Introduction • In general, a single strategy might be thought of as an algorithm or an operation • In the context of the Strategy design pattern, the idea is that there are multiple approaches to doing something, depending on certain conditions or context • The Strategy design pattern, then, depends on picking the approach or picking the strategy

  4. When there is more than one way to go about doing something, complexity can result • Not only are there the different implementations to consider • There is also the code that is devoted to making the choice of which strategy to use

  5. The purpose of the Strategy design pattern is to separate the implementations of different strategies from each other • It also separates the code for picking the strategy from the strategy implementations • The pattern defines a single interface for all strategies

  6. The separate strategies are implemented with a method of the same name in each of the classes implementing the interface • Which strategy is used will depend on what kind of object the method implementing the strategy is called on • The intent of the pattern is realized through an interface and depends on polymorphism and dynamic binding

  7. Book Definition of Pattern • Book definition: • The intent of Strategy is to encapsulate alternative approaches, or strategies, in separate classes that each implement a common operation.

  8. Modeling Strategies • Like with the previous chapters, and others, the book illustrates the Strategy design pattern in the following way: • It develops an example with multiple strategies that doesn’t use the Strategy design pattern • It then refactors the example using the Strategy design pattern

  9. Example Scenario • When a potential customer calls in, interested in buying fireworks, there is software which will make a recommendation or suggestion • There are several different ways a recommendation can be made: • Either a particular firework is being promoted, or two pieces of software, Rel8 or LikeMyStuff can make a recommendation, or a default option can be chosen

  10. Rel8 relies on a customer’s already being registered • During registration the customer specifies preferences in entertainment and fireworks • Rel8 makes a suggestion based on the similarity of the customer to other customers (presumably suggesting something that similar customers have tended to buy) • If the customer isn’t registered, Rel8 can’t be used

  11. LikeMyStuff doesn’t rely on pre-registration, but it does rely on customer information • The idea is that it will make a recommendation based on a profile of recent purchases by the customer • If not enough data can be obtained to form the profile, then LikeMyStuff can’t be used

  12. This is the default: • If none of the previous options applies, then a firework is suggested at random

  13. UML for the Scenario • The UML diagram on the following overhead shows the classes involved in the design as described so far • Appendix D on UML clarifies the notation: • “Use a dashed arrow between classes to show a dependency that does not use an object reference. For example, the Customer class relies on a static method from the LikeMyStuff recommendation engine.”

  14. The getRecommended() Method • Viewing the scenario from the top down, what you have is this: • The Customer class has a getRecommended() method in it • This method consists of if/else code which chooses one of the strategies, whether to do a promotion, or to use Rel8, LikeMyStuff, or the default

  15. Doing a Promotion • If there is a promotion underway, the first part of the logic of getRecommended() deals with that case • The logic for doing a promotion consists of looking up the contents of a file named strategy.dat in a directory named config • If there is such a file, its contents should look something like this: promote=JSquirrel

  16. The basic idea is that if the data file is not empty, the firework it contains is returned • If its contents come up null you go on to the next option • Also, if the file read doesn’t work, you don’t do anything in the catch block, you just continue on to the other options

  17. Using Rel8 • The Rel8 class has a method advise(), so getRecommended() wraps a call to that method if that strategy is selected • The call looks like this: • if(isRegistered()) • return (Firework) Rel8.advise(this); • “this” is the customer, and Rel8 relies entirely on the information contained in the registered customer object

  18. Using LikeMyStuff • The LikeMyStuff class has a suggest() method, so getRecommended() wraps a call to that method if that strategy is selected • The call looks like this: • if(spendingSince(cal.getTime()) > 1000) • return (Firework) LikeMyStuff.suggest(this); • “this” is the customer, and LikeMyStuff relies on a database of recent purchases by that customer, which is accessed by the call to spendingSince() on the customer

  19. The Firework class has a getRandom() method, so if all else fails, getRecommended() wraps a call to that method • The code for getRecommended() is shown on the following overheads • It is a collection of if statements. • It is unfortunate that it is not organized as a sequence of if/else if’s.

  20. The Code for getRecommended() • public Firework getRecommended() • { • // if promoting a particular firework, return it • try • { • Properties p = new Properties(); • p.load(ClassLoader.getSystemResourceAsStream(“config/strategy.dat”)); • String promotedName = p.getProperty(“promote”); • if(promotedName != null) • { • Firework f = Firework.lookup(promotedName); • if(f != null) • return f; • }

  21. catch(Exception ignored) • { • // If resource is missing or it failed to load, • // fall through to the next approach. • } • // if registered, compare to other customers • if(isRegistered()) • { • return (Firework) Rel8.advise(this); • }

  22. // check spending over the last year • Calendar cal = Calendar.getInstance(); • cal.add(Calendar.YEAR, -1); • if(spendingSince(cal.getTime()) > 1000) • return (Firework) LikeMyStuff.suggest(this); • // oh well! • return Firework.getRandom(); • }

  23. What’s Wrong with the Initial Design • The book identifies two basic problems with the getRecommended() method as given: • It’s too long • It combines both selecting a strategy and executing it

  24. This is actually one of the high points of the book • It explains that you know that the method is too long because you need to put comments in it • “Short methods are easy to understand, seldom need explanation…”

  25. Finally, what every student always knew: Comments are bad… • More accurately, you might facetiously say that code which requires comments is bad. • The book doesn’t say that putting a comment at the beginning for the whole method is bad. • A useful observation might be that a method should be short and sweet enough that it doesn’t need internal commenting.

  26. Refactoring to the Strategy Pattern • Applying the Strategy design pattern involves three things: • 1. Creating an interface that defines the strategic operation • 2. Writing classes that represent each strategy and implement the interface • 3. Refactoring the code to select and use an instance of the right strategy class

  27. The Interface • 1. The interface will be named Advisor • The interface requires that an implementing class have a method named recommend() • The recommend() method will take a customer as a parameter • It will return a firework • A UML diagram of the interface is given on the next overhead

  28. The Implementing Classes • 2. The next step is to create the classes that represent the different strategies and implement the interface • The book essentially presents this information as part of the following challenge

  29. Challenge 23.1 • Fill in the class diagram in Figure 23.3, which shows the recommendation logic refactored into a collection of strategy classes. • Comment mode on: • What they want is mindlessly simple • That will be clear when you see the answer

  30. Solution 23.1 • Figure B.24 shows one solution.

  31. The PromotionAdvisor and RandomAdvisor class names should be self-explanatory • GroupAdvisor refers to the use of Rel8 • ItemAdvisor refers to the use of LikeMyStuff • The implementations of the recommend() method for these classes will wrap a call to the static methods of Rel8 and LikeMyStuff • An expanded UML diagram for these two classes is given on the next overhead

  32. Making Instances of the Implementing Classes • An interface can’t define static methods • An interface defines what the book calls “object methods”—methods that are called on objects • Instances of GroupAdvisor and ItemAdvisor, the classes that implement the interface, are needed in order to call the methods defined in the interface an implemented in them

  33. Only one instance each of GroupAdvisor and ItemAdvisor are needed • In the refactored design, these instances will be static objects in the Customer class

  34. Code for the recommend() Method in the GroupAdvisor Class • This is what the recommend() method looks like in the GroupAdvisor class: • public Firework recommend(Customer c) • { • return (Firework) Rel8.advise(c); • } • By means of a wrapped call, the implementation of the method translates from the advise() interface of Rel8 to the recommend() interface of Advisor

  35. Code for the recommend() Method in the ItemAdvisorClass • The code for the recommend() method in the ItemAdvisor class is analogous. • The book doesn’t give it and it doesn’t even bother to give it as a challenge. • It should be straightforward to write that method.

  36. Challenge 23.2 • In addition to Strategy, what pattern appears in the GroupAdvisor and ItemAdvisor classes?

  37. Solution 23.2 • The GroupAdvisor and ItemAdvisor classes are instances of Adapter, providing the interface a client expects, using the services of a class with a different interface. • Comment mode on: • This wasn’t so hard—describing the wrapping of the call as “translating” kind of gave it away

  38. Code for the recommend() Method in the PromotionAdvisorClass • A PromotionAdvisor class is also needed, with a recommend() method • Most of the logic of the original code is moved into the constructor for the new class • If a promotion is on, then the promoted instance variable of the class is initialized

  39. In addition to the recommend() method, there is a hasItem() method which can be called to see whether a promoted item is available • Overall, the code is a bit messy because of the class loader logic and the try/catch blocks • The details of this technique will not be covered since they are extraneous to the design pattern • The code is shown on the following overheads

  40. public class PromotionAdvisor implements Advisor • { • private Firework promoted; • public PromotionAdvisor() • { • try • { • Properties p = new Properties(); • p.load(ClassLoader.getSystemResourceAsStream("config/strategy.dat")); • String promotedFireworkName = p.getProperty("promote"); • if (promotedFireworkName != null) • promoted = Firework.lookup(promotedFireworkName); • } • catch (Exception ignored) • { • // Resource not found or failed to load • promoted = null; • } • }

  41. public booleanhasItem() • { • return promoted != null; • } • public Firework recommend(Customer c) • { • return promoted; • } • }

  42. Code for the recommend() Method in the RandomAdvisorClass • The RandomAdvisor class is simple • Its code is shown on the following overhead

  43. public class RandomAdvisor implements Advisor • { • public Firework recommend(Customer c) • { • return Firework.getRandom(); • } • }

  44. Refactoring the Customer Class to Use the Interface • In order to make use of the recommend() method, a single instance of each of the advisor classes may be needed • The new customer class, Customer2, has these lines of code in it at the top: • private static PromotionAdvisorpromotionAdvisor = • new PromotionAdvisor(); • private static GroupAdvisorgroupAdvisor = • new GroupAdvisor(); • private static ItemAdvisoritemAdvisor = • new ItemAdvisor(); • private static RandomAdvisorrandomAdvisor = • new RandomAdvisor();

  45. Customer2 also contains a method named getAdvisor() for picking which kind of advisor to use • This code is organized around a sequence of if/else if statements • In other words, the logic for picking the advisor replaces the earlier code which called different strategies directly

More Related