21
Advanced OOD, Patterns and the Strategy Pattern 1

Advanced OOD, Patterns and the Strategy Patterncseweb.ucsd.edu/.../fa16/cse110-a/applications/ln/cse110-f16-lectur… · Three Ways to Declare Subtype in Java Subclass a class class

  • Upload
    others

  • View
    3

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Advanced OOD, Patterns and the Strategy Patterncseweb.ucsd.edu/.../fa16/cse110-a/applications/ln/cse110-f16-lectur… · Three Ways to Declare Subtype in Java Subclass a class class

Advanced OOD,

Patterns and the Strategy Pattern

1

Page 2: Advanced OOD, Patterns and the Strategy Patterncseweb.ucsd.edu/.../fa16/cse110-a/applications/ln/cse110-f16-lectur… · Three Ways to Declare Subtype in Java Subclass a class class

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

Page 3: Advanced OOD, Patterns and the Strategy Patterncseweb.ucsd.edu/.../fa16/cse110-a/applications/ln/cse110-f16-lectur… · Three Ways to Declare Subtype in Java Subclass a class class

Object-Oriented Typing

Rehash: Is-A vs Has-A vs Can-Do

Theory of Object-Oriented, III

3

Page 4: Advanced OOD, Patterns and the Strategy Patterncseweb.ucsd.edu/.../fa16/cse110-a/applications/ln/cse110-f16-lectur… · Three Ways to Declare Subtype in Java Subclass a class class

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

Page 5: Advanced OOD, Patterns and the Strategy Patterncseweb.ucsd.edu/.../fa16/cse110-a/applications/ln/cse110-f16-lectur… · Three Ways to Declare Subtype in Java Subclass a class class

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

Page 6: Advanced OOD, Patterns and the Strategy Patterncseweb.ucsd.edu/.../fa16/cse110-a/applications/ln/cse110-f16-lectur… · Three Ways to Declare Subtype in Java Subclass a class class

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

Page 7: Advanced OOD, Patterns and the Strategy Patterncseweb.ucsd.edu/.../fa16/cse110-a/applications/ln/cse110-f16-lectur… · Three Ways to Declare Subtype in Java Subclass a class class

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

Page 8: Advanced OOD, Patterns and the Strategy Patterncseweb.ucsd.edu/.../fa16/cse110-a/applications/ln/cse110-f16-lectur… · Three Ways to Declare Subtype in Java Subclass a class class

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

Page 9: Advanced OOD, Patterns and the Strategy Patterncseweb.ucsd.edu/.../fa16/cse110-a/applications/ln/cse110-f16-lectur… · Three Ways to Declare Subtype in Java Subclass a class class

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

Page 10: Advanced OOD, Patterns and the Strategy Patterncseweb.ucsd.edu/.../fa16/cse110-a/applications/ln/cse110-f16-lectur… · Three Ways to Declare Subtype in Java Subclass a class class

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

Page 11: Advanced OOD, Patterns and the Strategy Patterncseweb.ucsd.edu/.../fa16/cse110-a/applications/ln/cse110-f16-lectur… · Three Ways to Declare Subtype in Java Subclass a class class

Software Design Patterns

An Introduction

11

Page 12: Advanced OOD, Patterns and the Strategy Patterncseweb.ucsd.edu/.../fa16/cse110-a/applications/ln/cse110-f16-lectur… · Three Ways to Declare Subtype in Java Subclass a class class

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.

Page 13: Advanced OOD, Patterns and the Strategy Patterncseweb.ucsd.edu/.../fa16/cse110-a/applications/ln/cse110-f16-lectur… · Three Ways to Declare Subtype in Java Subclass a class class

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

Page 14: Advanced OOD, Patterns and the Strategy Patterncseweb.ucsd.edu/.../fa16/cse110-a/applications/ln/cse110-f16-lectur… · Three Ways to Declare Subtype in Java Subclass a class class

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

Page 15: Advanced OOD, Patterns and the Strategy Patterncseweb.ucsd.edu/.../fa16/cse110-a/applications/ln/cse110-f16-lectur… · Three Ways to Declare Subtype in Java Subclass a class class

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

Page 16: Advanced OOD, Patterns and the Strategy Patterncseweb.ucsd.edu/.../fa16/cse110-a/applications/ln/cse110-f16-lectur… · Three Ways to Declare Subtype in Java Subclass a class class

Strategy Pattern

Composition + Delegation + Interfaces

17

Page 17: Advanced OOD, Patterns and the Strategy Patterncseweb.ucsd.edu/.../fa16/cse110-a/applications/ln/cse110-f16-lectur… · Three Ways to Declare Subtype in Java Subclass a class class

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

Page 18: Advanced OOD, Patterns and the Strategy Patterncseweb.ucsd.edu/.../fa16/cse110-a/applications/ln/cse110-f16-lectur… · Three Ways to Declare Subtype in Java Subclass a class class

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

Page 19: Advanced OOD, Patterns and the Strategy Patterncseweb.ucsd.edu/.../fa16/cse110-a/applications/ln/cse110-f16-lectur… · Three Ways to Declare Subtype in Java Subclass a class class

Shopping Cart

class ShoppingCart {

DiscountCalculator discountCalculator;

public ShoppingCart(Customer c) {

discount = c.getDiscountCalculator();

}

int finalPriceCents () {

return total * (1 – discountCalculator.getDiscount());

}

20

Page 20: Advanced OOD, Patterns and the Strategy Patterncseweb.ucsd.edu/.../fa16/cse110-a/applications/ln/cse110-f16-lectur… · Three Ways to Declare Subtype in Java Subclass a class class

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

Page 21: Advanced OOD, Patterns and the Strategy Patterncseweb.ucsd.edu/.../fa16/cse110-a/applications/ln/cse110-f16-lectur… · Three Ways to Declare Subtype in Java Subclass a class class

Widely Used for Algorithm Alternatives

22