Upload
others
View
3
Download
0
Embed Size (px)
Citation preview
Advanced OOD,
Patterns and the Strategy Pattern
1
From Requirements to
Object-Oriented Design
2
As a user
I want see my nearby friends on the map
So that I know who to contact for a spontaneous meet-up
class Friend {Location location(); // null −> not-knownboolean online();Bitmap image();}
class Friends implements Iterable<Friend> {Friends online();Friends locationKnown(); // −> 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)
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
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 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
4
Mammal
Feline Canine
Tiger House Cat
• 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
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
5
Mammal
Feline Canine
Tiger House Cat
void petFur(Mammal m) {
int coarseness = m.furValue();
…
}
• Use of a supertype variable like Mammal
allows all current and future subtypes of
Mammal to be petted
• petFur will work for Canine subclass Dog
when it is added
• We say that petFur is open for extension
Three Ways to Declare Subtype in Java
Subclass a class class Mammal {…}
class Feline extends Mammal {…}
Feline is a subtype of Mammal
Feline gets all of Mammal’s implementation (can override)
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 HouseCat extends Feline implements Cuddly {…}6
Mammal
Feline Canine
Tiger House Cat
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
Can “mix in” all the supertypes you want
Not just a tree of types anymore
7
Mammal
Feline Canine
Bengal Tiger Tabby
Spotted Cuddly
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 TinySet implements Set { /* linked list */ }
class BigSet 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 TinySet 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
Abstract class allows reusingsome common implementationamong Felines, and yet cannotbe new’d (instantiated).Interface is a reasonableanswer, too, as the sharing mightnot be too great.
9
Mammal
Feline Canine
Tiger House Cat
Interfaces are Central to Java
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 ListArray or HashSet, etc.
Requires no particular
implementation
Super-flexible
code
10
Software Design Patterns
An Introduction
11
Design Patterns, Generally?
13
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.
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 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 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
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.
18
https://en.wikipedia.org/wiki/Strategy_pattern#/media/File:Strategy_Pattern_in_UML.png
Shopping Cart, continued
class ShoppingCart {DiscountCalculator discountCalculator;…int finalPriceCents () {
return total * (1 – discountCalculator.getDiscount());}
interface unsigned float DiscountCalculator {unsigned float getDiscount();
}
class ClubCustomer implements DiscountCalculator {…public unsigned float getDiscount() {
return (1 – MAX_DISCOUNT);}
}
class RetailCustomer implements DiscountCalculator {…public unsigned float getDiscount() {
unsigned float discount = points /POINTS_PER_DPERCENT);return (discount > MAX_DISCOUNT, 1 – discount, 1 – MAX_DISCOUNT);
}
19
Shopping Cart
class ShoppingCart {
DiscountCalculator discountCalculator;
public ShoppingCart(Customer c) {
discount = c.getDiscountCalculator();
}
…
int finalPriceCents () {
return total * (1 – discountCalculator.getDiscount());
}
20
Car Description: What’s Wrong?
abstract class CarDesc {Color paintColor();
int wheelbase();…
int tireSize();
boolean tirePerf();
String tireSeason(); /* should be enum */}
abstract class SmallCar extends CarDesc {…
}
class KiaSoul extends SmallCar {
…
int tireSize() { return 165; }
boolean tirePerf() { return false; }
String tireSeason() { return “All”; }
A. CarDesc and maybe SmallCar
should be an interface
B. All these classes should
“implement” a Tire interface
C. KiaSoul should have a Tire
As implemented, KiaSoul 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.)
21
Widely Used for Algorithm Alternatives
22