Advanced OOD Patterns and the Strategy Pattern 1

  • Slides: 21
Download presentation
Advanced OOD, Patterns and the Strategy Pattern 1

Advanced OOD, Patterns and the Strategy Pattern 1

From Requirements to Object-Oriented Design As a user I want see my nearby friends

From Requirements to Object-Oriented Design As a user I want see my nearby friends on the map So that I know who to contact for a spontaneous meet-up Given I am logged in And my location is known When my friends are online And my friends’ location is known And my friends are near me Then I see them on the map class Friend { Location location(); // null −> not-known boolean online(); Bitmap image(); } class Friends implements Iterable<Friend> { Friends online(); Friends location. Known(); // −> online? } 1. Identify the “things” me (previous user story) friends, friend map (previous, built-in) 2. Identify the messages me. logged-in (previous) friend. location-known friend. location friend. online friend. near(me) friend. image 3. Assemble into classes 4. Right things call right messages (TBD) 2

Object-Oriented Typing Rehash: Is-A vs Has-A vs Can-Do Theory of Object-Oriented, III 3

Object-Oriented Typing Rehash: Is-A vs Has-A vs Can-Do Theory of Object-Oriented, III 3

Typing and Subtyping: “is a” In Object-Oriented, it’s all about behavior A particular behavior

Typing and Subtyping: “is a” In Object-Oriented, it’s all about behavior A particular behavior is described by a type Mammalian behavior is the Mammal type Tiger behavior is the Tiger type Because a Tiger always behaves like a Mammal, we say that Tiger is a subtype of Mammal Feline Tiger House Cat Canine • Feline is a subtype of Mammal • House Cat is a subtype of Feline • s Subtype c means all s’s always act like a c but not all c’s act like an s • All Felines are Mammals • But not all Mammals are Felines • Means that Feline object will always work wherever a Mammal is needed 4

Typing and Subtyping: “is a” (II) Feline a subtype of Mammal means Mammal a

Typing and Subtyping: “is a” (II) Feline a subtype of Mammal means Mammal a supertype of Feline A supertype variable can hold values of any of its subtypes void pet. Fur(Mammal m) { int coarseness = m. fur. Value(); … } Mammal Feline Tiger House Cat Canine • Use of a supertype variable like Mammal allows all current and future subtypes of Mammal to be petted • pet. Fur will work for Canine subclass Dog when it is added • We say that pet. Fur is open for extension 5

Three Ways to Declare Subtype in Java Subclass a class Mammal Feline class Mammal

Three Ways to Declare Subtype in Java Subclass a class Mammal Feline class Mammal {…} class Feline extends Mammal {…} Tiger House Cat Feline is a subtype of Mammal Feline gets all of Mammal’s implementation (can override) Canine Subclassing abstract class is similar Can’t “new” an abstract C b/c not all methods implemented abstract class Mammal {…} class Feline extends Mammal {…} Feline must implement missing methods of Mammal Abstract class asserts “I’m a category of thing, not a real thing” Interface has no methods implemented Like a totally abstract class interface Cuddly {…} class House. Cat extends Feline implements Cuddly {…} 6

More on Interfaces In Java, a class can extend just one superclass But a

More on Interfaces In Java, a class can extend just one superclass But a class can implement multiple interfaces interface Cuddly {…} interface Spotted {…} class Tabby extends Feline implements Cuddly, Spotted {…} Means interfaces are much more flexible Mammal Can “mix in” all the supertypes you want Feline Not just a tree of types anymore Canine Spotted Cuddly Bengal Tiger Tabby 7

More on Interfaces, II Not all classes represent a unique type Maybe want another

More on Interfaces, II Not all classes represent a unique type Maybe want another impl of same thing for performance, say Consider two possible impl’s of Set class Tiny. Set implements Set { /* linked list */ } class Big. Set implements Set { /* uses hard disk */ } Identical interfaces, input/output behavior −> same type One faster for tiny sets, the other faster for big sets Use interfaces for implementation alternatives Since Tiny. Set real subtype, extends would be misleading Since no shared implementation, extends would be misleading 8

How represent Feline (and Why)? A. Class B. Abstract Class C. Interface D. Extends

How represent Feline (and Why)? A. Class B. Abstract Class C. Interface D. Extends Abstract class allows reusing some common implementation among Felines, and yet cannot be new’d (instantiated). Interface is a reasonable answer, too, as the sharing might not be too great. Mammal Feline Tiger Canine House Cat 9

Interfaces are Central to Java Collections Framework Interface Collection methods like add(Object) & contains(Object)

Interfaces are Central to Java Collections Framework Interface Collection methods like add(Object) & contains(Object) interface List extends Collection … interface Set extends Collection … … Wherever Collection variable appears, allows for a a List. Array or Hash. Set, etc. Requires no particular implementation Super-flexible code 10

Software Design Patterns An Introduction 11

Software Design Patterns An Introduction 11

Design Patterns, Generally? Consider designing a kitchen Common challenges Need a sink, a stove/oven,

Design Patterns, Generally? Consider designing a kitchen Common challenges Need a sink, a stove/oven, a refrigerator, likely a dishwasher Needs counter space, and don’t want doors and drawers to collide Need space to stand Common patterns for a solution One-wall, Galley, L-shaped, U-Shaped, Peninsula, “Working triangle” (Refrigerator, range, sink) Same is true for basic bathroom Tub is 5’ x 2. 5 -31, Sink is 2 -2. 5’, Toilet is 1. 5 -2’ Overall minimum dimension is 5’ x 7’ Tub must go against wall – can’t cross Don’t want to see toilet from door and toilets longer than sinks Standard solution Sink, Toilet, Tub, with door in front of sink. 13

Design Patterns, Generally? Bedrooms upstairs; Kitchen, Dining room, main room downstairs Privacy for family

Design Patterns, Generally? Bedrooms upstairs; Kitchen, Dining room, main room downstairs Privacy for family spaces, downstairs for entertaining Master bedroom on third floor Privacy for parents or guests One bedroom on lower level Gives privacy from family level Doubles as “quiet room” near activity, e. g. office, hobby room or den You see the idea Experience leads to an understanding of common challenges And common solutions to those challenges Education leads to learning about these without needing to experience them Learn to spot the common challenges and consider the common patterns for addressing them Also gives us a way of talking about things, e. g. “Galley” or “Working Triangle” or “Master suite”, or “Multi-Purpose Den” 14

Software Design Patterns The same is true of software Common challenges Good ways of

Software Design Patterns The same is true of software Common challenges Good ways of addressing these challenges Great way of passing on and receiving experience Common vocabulary and building blocks for conversation Shared expectation about design and code structure Key Elements Name, or we can’t talk about it Common, interesting problem Good, exemplar solution A teaching, i. e. what makes the pattern worth learning Consensus, agreement about above and acceptance into vernacular Just like patterns for the design of physical spaces, software design patterns aren’t actual solutions to specific real problems, they are ideas that can be applied in many circumstances Idioms are implementations of patterns, i. e. in specific languages 15

Software Design Patterns Tricks Identifying common problems Separating common problems from context and arbitrary

Software Design Patterns Tricks Identifying common problems Separating common problems from context and arbitrary complexity For example, software design patterns aren’t accepted work-around for language specific issues, these are idioms Good solutions, articulating teaching Promulgation and acceptance 16

Strategy Pattern Composition + Delegation + Interfaces 17

Strategy Pattern Composition + Delegation + Interfaces 17

Strategy Pattern Name: Strategy Pattern, a. k. a. Policy Pattern Challenge: Runtime selection of

Strategy Pattern Name: Strategy Pattern, a. k. a. Policy Pattern Challenge: Runtime selection of mechanism for implementing a particular behavior, e. g. choosing the best algorithm for the circumstances Solution: Define the methods via an interface, that abstracts the behavior and its arguments from the implementation. At runtime, a reference via this interface can be associated with an instance with the proper implementation. Teaching: Interface references can enable interchangeable strategies, i. e. algorithms, at runtime. https: //en. wikipedia. org/wiki/Strategy_pattern#/media/File: Strategy_Pattern_in_UML. png 18

Shopping Cart, continued class Shopping. Cart { Discount. Calculator discount. Calculator; … int final.

Shopping Cart, continued class Shopping. Cart { Discount. Calculator discount. Calculator; … int final. Price. Cents () { return total * (1 – discount. Calculator. get. Discount()); } interface unsigned float Discount. Calculator { unsigned float get. Discount(); } class Club. Customer implements Discount. Calculator { … public unsigned float get. Discount() { return (1 – MAX_DISCOUNT); } } class Retail. Customer implements Discount. Calculator { … public unsigned float get. Discount() { unsigned float discount = points /POINTS_PER_DPERCENT); return (discount > MAX_DISCOUNT, 1 – discount, 1 – MAX_DISCOUNT); } 19

Shopping Cart class Shopping. Cart { Discount. Calculator discount. Calculator; public Shopping. Cart(Customer c)

Shopping Cart class Shopping. Cart { Discount. Calculator discount. Calculator; public Shopping. Cart(Customer c) { discount = c. get. Discount. Calculator(); } … int final. Price. Cents () { return total * (1 – discount. Calculator. get. Discount()); } 20

Car Description: What’s Wrong? abstract class Car. Desc { Color paint. Color(); int wheelbase();

Car Description: What’s Wrong? abstract class Car. Desc { Color paint. Color(); int wheelbase(); … int tire. Size(); boolean tire. Perf(); String tire. Season(); /* should be enum */ } A. Car. Desc and maybe Small. Car should be an interface abstract class Small. Car extends Car. Desc { … } As implemented, Kia. Soul only allows one set of values for tire behavior. By adding a Tire via an instance variable and delegating to its function, then all sorts of tires will beas an possible. (See next slide. ) class Kia. Soul extends Small. Car { … int tire. Size() { return 165; } boolean tire. Perf() { return false; } String tire. Season() { return “All”; } B. All these classes should “implement” a Tire interface C. Kia. Soul should have a Tire 21

Widely Used for Algorithm Alternatives 22

Widely Used for Algorithm Alternatives 22