design patterns design by abstraction n.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
Design Patterns: Design by Abstraction PowerPoint Presentation
Download Presentation
Design Patterns: Design by Abstraction

Loading in 2 Seconds...

play fullscreen
1 / 49

Design Patterns: Design by Abstraction - PowerPoint PPT Presentation


  • 107 Views
  • Uploaded on

Design Patterns: Design by Abstraction. CS 3331 Fall 2009. Outline. Design pattern Reusable component Template method Strategy pattern Factory pattern. Planet. Moon. Sun. Motivation . Modeling the solar system. 1..*. 0..*.

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'Design Patterns: Design by Abstraction' - ostinmannual


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.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
outline
Outline
  • Design pattern
  • Reusable component
  • Template method
  • Strategy pattern
  • Factory pattern
motivation

Planet

Moon

Sun

Motivation

Modeling the solar system

1..*

0..*

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

in java
In Java …

public class Sun {

private static Sun theInstance = new Sun();

private Sun() { /* … */ }

public static Sun getInstance() {

return theInstance;

}

// the rest of code …

}

in general

return theInstance;

In General …
  • T
  • - theInstance: T { static }
  • T()
  • + getInstance(): T { static }
singleton design pattern
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
example
Example
  • Define a Calendar class using the Singleton pattern.

public class Calendar {

// the rest of code …

}

what are design patterns
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.
why design patterns
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.
gof patterns
GoF Patterns

Creational Structural Behavioral

Abstract FactoryAdapter Chain of Responsibility

Builder Bridge Command

Factory Method Composite Interpreter

Prototype DecoratorIterator

Singleton Façade Mediator

Flyweight Memento

Proxy Observer

State

Strategy

Template Method

Visitor

E. Gamma, R. Helm, R. Johnson, and J. Vlissides. Design Patterns, Elements of Reusable

Object-Oriented Software, Addison-Wesley, 1995.

outline1
Outline
  • Design pattern
  • Reusable component
  • Template method
  • Strategy pattern
  • Factory pattern
generic components
Generic 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 of designing generic components
    • Refactoring
    • Generalizing
refactoring
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)
    • Capture the logic in a generic component
    • Restructure by replacing every occurrence of the code segment with a reference to the generic component
refactoring duplication
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
refactoring by inheritance
Refactoring by Inheritance

Sample code: any duplicate?

class A {

void m1() {

// …

step1();

step2();

step3();

// …

}

// …

}

class B {

void m2() {

// …

step1();

step2();

step3();

// …

}

// …

}

refactored code
Refactored Code

class A extends C {

void m1() {

// …

computeAll();

// …

}

// …

}

class B extends C {

void m2() {

// …

computeAll();

// …

}

// …

}

class C {

void computeAll() {

step1();

step2();

step3();

}

}

refactoring by delegation
Refactoring by Delegation

class A {

void m1() {

// …

h.computeAll();

// …

}

Helper h;

}

class B {

void m2() {

// …

h.computeAll();

// …

}

Helper h;

}

class Helper {

void computeAll() {

step1();

step2();

step3();

}

}

Q. Compare two approaches of

refactoring.

exercise

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

}

public class Point {

public Point(int x, int y) {

this.x = x;

this.y = y;

}

protected int x, y;

// other code;

}

Exercise

Identify and remove duplicate code.

generic animation applet

Applet

Timer

Generic Animation Applet
  • Reusable class that supports the animation idiom

timer

AnimationApplet

{abstract}

# delay: int

# dim: Dimension

+ init()

+ start()

+ stop()

animation applet cont
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, new ActionListener() {

public void actionPerformed(ActionEvent event) {

repaint();

}

});

}

<<continue to the next page>>

animation applet cont1
Animation Applet (Cont.)

public void start() {

timer.start();

}

public void stop() {

timer.stop();

}

}

using animation applet

DigitalClock

init()

start()

stop()

paint()

AnimationApplet

DigitalClock

paint()

Using Animation Applet
  • Reimplement the DigitalClock applet to use the animation applet class.
generic double buffered animation applet

Graphics

Applet

Image

DBAnimationApplet

{abstract}

init()

initAnimation()

update()

paint()

paintFrame() {abstract}

AnimationApplet

{abstract}

Generic Double-Buffered AnimationApplet
  • Reusable class that supports double-buffered animation

image

offScreen

db animation applet cont
DB Animation Applet (Cont.)

public abstract class DBAnimationApplet extends AnimationApplet {

<<constructors>>

<<initialization>>

<<updating and painting>>

protected Image image;

protected Graphics offscreen;

protected boolean doubleBuffered;

}

constructors
Constructors

protected DBAnimationApplet(boolean doubleBuffered) {

this.doubleBuffered = doubleBuffered;

}

protected DBAnimationApplet() {

this(true);

}

  • Question
    • Why protected constructors?
initialization
Initialization

final 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?
updating and painting
Updating and Painting

final public void update(Graphics g) {

if (doubleBuffered) {

paintFrame(offscreen);

g.drawImage(image, 0, 0, this);

} else {

super.update(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?
example1

DBAnimationApplet

init()

initAnimator()

update()

paint()

paintFrame()

BouncingBall

initAnimator()

paintFrame()

Example
  • Rewrite the bouncing ball applet to use the DBAnimationApplet class.
  • Note that:
    • init() calls initAnimation() which is
    • overridden in the subclass, and
    • Both update() and paint() call
    • paintFrame() which is overridden
    • in the subclass.
template methods

hookMethod1()

hookMethod2()

AbstractClass

templateMethod()

hookMethod1()

hookMethod2()

ConcreteClass

hookMethod1()

hookMethod2()

Template Methods
  • Intent
    • To define a skeleton algorithm by deferring some steps to subclasses
    • To allow the subclasses to redefine certain steps
template methods cont
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
exercise1
Exercise
  • Identify hook methods and template methods in the DBAnimationApplet class.
more example

PlotSine

func()

PlotCosine

func()

More Example
  • Generic function plotter
    • To plot arbitrary single-variable functions on a two-dimensional space

Plotter

func()

paint()

plotFunction()

drawCoordinates()

Applet

func()

exercise2

Rectangular

imaginary

(x, y)

y

x

real

Exercise

Complex numbers, x + y*i

Polar

(r, a)

r

a

exercise cont

Complex

add()

mul()

realPart()

imaginaryPart()

magnitude()

angle()

RectangularComplex

realPart()

imaginaryPart()

magnitude()

angle()

PolarComplex

realPart()

imaginaryPart()

magnitude()

angle()

Exercise (Cont.)
exercise cont1
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) {

}

outline2
Outline
  • Design pattern
  • Reusable component
  • Template method
  • Strategy pattern
  • Factory pattern
generalization
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
review

PlotSine

func()

PlotCosine

func()

Review
  • Generic function plotter
    • To plot arbitrary single-variable functions on a two-dimensional space

Plotter

func()

paint()

plotFunction()

drawCoordinates()

Applet

func()

generic multiple function plotter

Plotter

func()

paint()

plotFunction()

drawCoordinates()

Sine

apply()

Cosine

apply()

PlotSineCosine

initMultiPlotter()

Generic Multiple Function Plotter

Applet

1..*

Function

apply()

MultiPlotter

initMultiPlotter()

init()

addFunction()

plotFunction()

func()

<<create>>

<<create>>

multiple function plotter cont
Multiple Function Plotter (Cont.)

Method Description

initMultiPlotter() Hook method for subclasses to set up

functions to be plotted

init() Template method for initialization

which calls initMultiPlotter()

addFunction() Method to add a function to be plotted

plotFunction() Auxiliary function called by paint()

to plot the functions

func() Method inherited from class Plotter

that is no longer useful in this class

strategy design pattern

Strategy

alogorithm()

Context

contextMethod()

ConcreteStrategyA

algorithm()

ConcreteStrategyB

algorithm()

strategy

strategy.algorithm()

Strategy Design Pattern
  • Intent
    • To define a family of algorithms, encapsulate each one, and make them interchangeable
question
Question
  • Have we used the Strategy Pattern before?
abstract coupling
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?
design guideline
Design Guideline
  • Program to an interface, not to an implementation!
iterating over collection
Iterating over Collection
  • Accessing all elements of collection objects such as sets, bags, lists, etc.

Collection c;

c = new ArrayList();

for (Iterator i = c.iterator(); i.hasNext(); ) {

Object elem = i.next();

}

iterator pattern

Iterator

hasNext()

next()

ConcreteIterator

hasNext()

next()

Collection

iterator()

ConcreteCollection

iterator()

Iterator Pattern
  • Intent
    • To provide a way to access the elements of a collection sequentially

<<create>>

return new ConcreteIterator()

exercise3
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 books() { return new LibraryIterator(books); }

private static class LibraryIterator implements java.util.Iterator {

public void remove() { throw new UnsupportedOperationException(); }

// YOUR CODE HERE …

}

}

factory design pattern

AbstractFactory

makeProduct()

ConcreteFactory

makeProduct()

Client

Factory Design Pattern
  • 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

Product

create

ConcreteProuct

example2

ComplexFactory

makeComplext()

PolarFactory

makeComplex()

RectangularFactory

makeComplex()

Example
  • Complex numbers

Complex

<<create>>

PolarComplex

<<create>>

RectangularComplex