design patterns: design by abstraction cs 3331 chapter 7 of [jia03]

52
Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

Upload: derrick-fox

Post on 17-Jan-2016

214 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

Design Patterns: Design by Abstraction

CS 3331

Chapter 7 of [Jia03]

Page 2: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

2

Outline

Design pattern Reusable component Template method Strategy pattern Factory pattern

Page 3: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

3

Motivation

Q: How to make sure that there exists only one Sun object in the system?

Modeling the solar system

1..*Planet MoonSun

0..*

Page 4: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

4

In Java …

public class Sun { private static Sun theInstance = new Sun(); private Sun() { /* … */ } public static Sun getInstance() { return theInstance; } // the rest of code …}

Page 5: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

5

In General …

T

- theInstance: T { static }

- T()+ getInstance(): T { static }

return theInstance;

Page 6: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

6

Singleton Design Pattern

Intent To ensure that a class has only one instance and

provides a global access point to it

Applicability Use the Singleton pattern when there must be exactly

one instance of a class and it must be accessible to clients from a well-known access point

Benefits Controlled access to the sole instance Permits a variable number of instances

Page 7: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

7

Example Define a Calendar class using the Singleton pattern.

public class Calendar {

// the rest of code …}

Page 8: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

8

What Are Design Patterns?

Design patterns are: Schematic descriptions of design solutions to

recurring problems in software design, and Reusable (i.e., generic), but don’t have to be

implemented in the same way. That is, describe:

Design problems that occur repeatedly, and Core solutions to those problems.

Page 9: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

9

Why Design Patterns?

To capture and document software design knowledge.

=> helps designers acquire design expertise. To support reuse in design and boost

confidence in software systems. To provide a common vocabulary for software

designers to communicate their designs.

Page 10: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

10

GoF Patterns

Creational Structural Behavioral

Abstract Factory Adapter Chain of ResponsibilityBuilder Bridge CommandFactory Method Composite InterpreterPrototype Decorator IteratorSingleton Façade Mediator

Flyweight MementoProxy Observer

StateStrategyTemplate MethodVisitor

E. Gamma, R. Helm, R. Johnson, and J. Vlissides. Design Patterns, Elements of ReusableObject-Oriented Software, Addison-Wesley, 1995.

Page 11: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

11

Outline

Design pattern Reusable component Template method Strategy pattern Factory pattern

Page 12: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

12

Generic (Reusable) Components Generic components

Program components (e.g., classes and packages) that can be extended, adapted, and reused in many different contexts without having to modify the source code

Also known as reusable components Techniques for designing generic components

Refactoring Generalizing

Page 13: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

13

Refactoring Definition

Refactoring means restructuring a program to improve its structure (e.g., to eliminate duplicate code segments) without changing its functionality

Approach Identify code segment that implements the same logic

(e.g., duplicate code)=> Commonality and variability analysis

Capture the logic in a generic component Restructure by replacing every occurrence of the code

segment with a reference to the generic component

Page 14: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

14

Refactoring Duplication Why?

Hazardous for maintenance Changes must be repeated everywhere Some may be overlooked or forgotten Thus, code segments can easily drift apart

Approach Refactoring by inheritance Refactoring by delegation

Page 15: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

15

Refactoring by Inheritance

class A { void m1() { // … step1(); step2(); step3(); // … } // …}

class B { void m2() { // … step1(); step2(); step3(); // … } // …}

Sample code: any duplicate?

Page 16: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

16

Refactored Code

class C { void computeAll() { step1(); step2(); step3(); }}

class A extends C { void m1() { // … computeAll(); // … } // …}

class B extends C { void m2() { // … computeAll(); // … } // …}

Page 17: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

17

Refactoring by Delegation

class Helper { void computeAll() { step1(); step2(); step3(); }}

class A { void m1() { // … h.computeAll(); // … } Helper h;}

class B { void m2() { // … h.computeAll(); // … } Helper h;}

Q. Compare the two?

Page 18: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

18

Exercise

public class Point { public Point(int x, int y) { this.x = x; this.y = y; } protected int x, y; // other code;}

public class ColoredPoint extends Point { public ColoredPoint(int x, int y, Color c) { this.x = x; this.y = y; this.c = c; } protected Color c; // other code}

Identify and remove duplicate code.

Page 19: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

19

Generic Animation Applet

Reusable class that supports the animation idiom

Applet

AnimationApplet {abstract}

# delay: int# dim: Dimension

+ init()+ start()+ stop()

Timertimer

Page 20: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

20

Animation Applet (Cont.)public abstract class AnimationApplet extends java.applet.Applet {

protected Timer timer; protected int delay = 100; protected Dimension dim;

public void init() { dim = getSize(); String att = getParameter(“delay”); if (att != null ) { delay = Integer.parseInt(att); } timer = new Timer(delay, e -> repaint()); }

<<continue to the next page>>

Page 21: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

21

Animation Applet (Cont.) public void start() { timer.start(); }

public void stop() { timer.stop(); }}

Page 22: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

22

Using Animation Applet

Reimplement the DigitalClock applet to use the animation applet class.

DigitalClock

init()start()stop()paint()

DigitalClock

paint()

AnimationApplet

Page 23: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

23

Generic Double-Buffered AnimationApplet

Reusable class that supports double-buffered animation

Applet

DBAnimationApplet {abstract}

init()initAnimation()update()paint()paintFrame() {abstract}

AnimationApplet{abstract}

Image

Graphics

image

offScreen

Page 24: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

24

DB Animation Applet (Cont.)public abstract class DBAnimationApplet extends AnimationApplet { protected Image image; protected Graphics offscreen; protected boolean doubleBuffered;

<<constructors>> <<initialization>> <<updating and painting>>

}

Page 25: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

25

Constructorsprotected DBAnimationApplet(boolean doubleBuffered) { this.doubleBuffered = doubleBuffered;}

protected DBAnimationApplet() { this(true);}

Question Why protected constructors?

Page 26: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

26

Initializationfinal public void init() { super.init(); image = createImage(dim.width, dim.height); offscreen = image.getGraphics(); initAnimator();}

protected void initAnimator() {}

Questions Why “final” init? Why “protected” and separate initAnimator? What’s the difference between constructors and

init methods?

Page 27: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

27

Updating and Paintingfinal public void update(Graphics g) { if (doubleBuffered) { paintFrame(offscreen); g.drawImage(image, 0, 0, this); } else { paintFrame(g); }}final public void paint(Graphics g) { update(g);}protected abstract void paintFrame(Graphics g);

Questions Why “final” update and paint, and why “abstract” paintFrame? How does this cater for both double-buffered and non-DB

animation?

Page 28: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

28

Example

Rewrite the bouncing ball applet to use the DBAnimationApplet class.

DBAnimationApplet

init()initAnimator()update()paint()paintFrame()

BouncingBall

initAnimator()paintFrame()

Note that:- init() calls initAnimation() which is overridden in the subclass, and- Both update() and paint() call paintFrame() which is overridden in the subclass.

Page 29: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

29

Bouncing Ball Animationpublic class BouncingBall extends DBAnimationApplet {

private int x, y; private int dx = -2, dy = -4; private int radius = 20; private Color color = Color.GREEN;

protected void initAnimator() { x = dim.width * 2 / 3; y = dim.height - radius; }

<< paintFrame method >>}

Page 30: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

30

Bouncing Ball Animation (Cont.) protected void paintFrame(Graphics g) { g.setColor(Color.BLACK); g.fillRect(0, 0, dim.width, dim.height);

if (x < radius || x > dim.width - radius) { dx = -dx; } if (y < radius || y > dim.height - radius) { dy = -dy; }

x += dx; y += dy;

g.setColor(color); g.fillOval(x - radius, y - radius, radius * 2, radius * 2); }

Page 31: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

31

Template Methods

Intent To define a skeleton algorithm by deferring some

steps to subclasses To allow the subclasses to redefine certain steps

AbstractClass

templateMethod()hookMethod1()hookMethod2()

ConcreteClass

hookMethod1()hookMethod2()

…hookMethod1()…hookMethod2()…

Page 32: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

32

Template Methods (Cont.)

Terminology Hook methods: placeholders for the behaviour

to be implemented by subclasses Template methods: methods containing hook

methods Hot spots: changeable behaviours of generic

classes represented by hook methods Frozen spots: fixed behaviours of generic

classes represented by template methods

Page 33: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

33

Exercise

Identify hook methods and template methods in the DBAnimationApplet class.

Page 34: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

34

Exercise: Solar System

Write an animation applet that shows the sun and a planet orbiting around the sun. Use the DBAnimationApplet class.

Page 35: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

35

More Example Generic function plotter

To plot arbitrary single-variable functions on a two-dimensional space

Plotter

func()paint()plotFunction()drawCoordinates()

PlotSine

func()

…func()…

Applet

PlotCosine

func()

Page 36: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

36

Exercise

(r, a)

r

a

Polar

(x, y)

x

y

Rectangular

real

imaginary

Complex numbers, x + y*i

Page 37: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

37

Exercise (Cont.)

Complex

add()mul()realPart()imaginaryPart()magnitude()angle()

RectangularComplex

realPart()imaginaryPart()magnitude()angle()

PolarComplex

realPart()imaginaryPart()magnitude()angle()

Page 38: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

38

Exercise (Cont.)Write the template methods add and mul.

// Assume constructors RectangularComplex(int real, int imag) and // PolarComplex(int magnitude, int angle).public Complex add(Complex c) {

}

public Complex mul(Complex c) {

}

Page 39: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

39

Outline

Design pattern Reusable component Template method Strategy pattern Factory pattern

Page 40: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

40

Generalization

Definition Process that takes a solution to a specific

problem and restructures it to solve a category of problems similar to the original problem

Example Generalize the plotter class to support multiple

functions

Page 41: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

41

Review Generic function plotter

To plot arbitrary single-variable functions on a two-dimensional space

Plotter

func()paint()plotFunction()drawCoordinates()

PlotSine

func()

…func()…

Applet

PlotCosine

func()

Page 42: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

42

Generic Multiple Function Plotter

Plotter

func()paint()plotFunction()drawCoordinates()

Sine

apply()

Applet

MultiPlotter

initMultiPlotter()init()addFunction()plotFunction()func()

PlotSineCosine

initMultiPlotter()

Cosine

apply()

Function

apply()

1..*

<<create>>

<<create>>

Page 43: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

43

Multiple Function Plotter (Cont.)

Method Description

initMultiPlotter() Hook method for subclasses to set upfunctions to be plotted

init() Template method for initializationwhich calls initMultiPlotter()

addFunction() Method to add a function to be plottedplotFunction() Auxiliary function called by paint()

to plot the functions

func() Method inherited from class Plotterthat is no longer useful in this class

Page 44: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

44

Strategy Design Pattern

Context

contextMethod()

strategy

ConcreteStrategyA

algorithm()

Strategy

alogorithm()

ConcreteStrategyB

algorithm()

Intent To define a family of algorithms, encapsulate

each one, and make them interchangeable

strategy.algorithm()

Page 45: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

45

Question

Have we used the Strategy Pattern before?

Page 46: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

46

Abstract Coupling Definition

Abstract coupling means a client access a service through an interface or an abstract class without knowing the actual concrete class that provide the service

Example Strategy pattern Iterator pattern

Question Why abstract coupling?

Page 47: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

47

Design Guideline

Program to an interface, not to an implementation!

Page 48: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

48

Iterating over Collection

Collection<T> c;…c= new ArrayList<>();…for (Iterator<T> i = c.iterator(); i.hasNext(); ) { T elem = i.next(); …}

// since Java 5 if c is of type Iterable<T>for (T elem: c) { … elem …}

Accessing all elements of collection objects such as sets, bags, lists, etc.

Page 49: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

49

Iterator Pattern

Collection

iterator()

Iterator

hasNext()next()

ConcreteCollection

iterator()

ConcreteIterator

hasNext()next()

<<create>>

return new ConcreteIterator()

Intent To provide a way to access the elements of a

collection sequentially

<<use>>

Page 50: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

50

Exercise Fill out the missing part to implement the Iterator interface

public class Library { private Book[] books; /** Returns an iterator enumerating all books of this library. */ public Iterator<Book> books() { return new LibraryIterator(books); }

private static class LibraryIterator implements java.util.Iterator<Book> { public void remove() { throw new UnsupportedOperationException(); } // YOUR CODE HERE …

}}

Page 51: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

51

Factory Design Pattern

AbstractFactory

makeProduct()

Product

ConcreteFactory

makeProduct()

ConcreteProuctcreate

Client

Intent To decouple object creation from its use and to

support different way of creating objects To define an interface for creating objects but let

subclasses decide which class to instantiate and how

Page 52: Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

52

Example Complex numbers

ComplexFactory

makeComplext() Complex

PolarFactory

makeComplex()

<<create>>RectangularFactory

makeComplex()

PolarComplex

RectangularComplex

<<create>>