2/10/15 Today s goals Design Patterns What are Design Patterns? - - PDF document

2 10 15
SMART_READER_LITE
LIVE PREVIEW

2/10/15 Today s goals Design Patterns What are Design Patterns? - - PDF document

2/10/15 Today s goals Design Patterns What are Design Patterns? Announcements: Thank you for your Early Informal Feedback Composite, Visitor, HW3 Phase 2, peer reviews due this Thu at Template Method, Faade, 5pm


slide-1
SLIDE 1

2/10/15 1

1

Design Patterns

Composite, Visitor, Template Method, Façade, Adapter Examples from Eclipse

cs361

Today’s goals

❚ What are Design Patterns? ❚ Announcements:

❙ Thank you for your Early Informal Feedback ❙ HW3 – Phase 2, peer reviews due this Thu at 5pm

cs361 2 cs361 3

How to Design

❚ Problem

❙ Model the problem, analysis, requirements

❚ Patterns

❙ Remember similar solutions

❚ Patch

❙ Test and fix, repair

Defining Patterns

Design Patterns – expert solutions to recurring problems in a certain domain Description usually involves problem definition, driving forces, solution, benefits, difficulties, related patterns. Pattern Language - a collection of patterns, guiding the users through the decision process in building a system Patterns are related (high level-low level)

4

Definition

  • we get hungry every lunch hour.
  • usually around 11:30am – 1:00pm.
  • must resolve hunger.

Driving Forces

  • appetite, intensity of hunger,

nearby restaurants Solution

  • eat at nearest restaurant that satisfies

minimum appetite requirement. Benefits

  • hunger is resolved

Difficulties

  • must not fall asleep afterwards.

Related Patterns

  • dinner, breakfast, brunch, and snack

Example Design Space

“Lunch” Pattern “Eat” Pattern Language

Wake-Up Breakfast Lunch Dinner Brunch

5 cs361 6

Software Patterns

❚ Experts build up a set of techniques ❚ “Best practices” - good enough practices ❚ Patterns

❙ Recurring arrangements of elements ❙ Documenting expertise ❙ An excuse to describe something that doesn’t fall into standard categories (algorithm, data structure)

slide-2
SLIDE 2

2/10/15 2

cs361 7

Design Patterns: Elements of Reusable Object-Oriented Software ❚ Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides ❚ Addison-Wesley 1995 ❚ 23 object-oriented patterns

Lots of books on patterns

cs361 1-8

Fundamental OO design principles

❚ Open-Closed principle:

❙ “classes should be open for extension, but closed for modification”

❚ Distribute the implementation

❙ Don’t have one object that gets too complicated and too smart. Each object knows how to do it’s small part.

cs361 1-9 cs361 10

Composite design pattern

❚ Context:

❙ Developing OO software

❚ Problem:

❙ Complex part-whole hierarchy has lots of similar classes.

❘ Example: document, chapter, section, paragraph. ❘ Want to be able to seamlessly add new parts

cs361 11

Forces

❙ power -- create new kind of part by composing existing ones ❙ simplicity -- treat composition of parts like a part ❙ safety -- no special cases, treat everything the same

cs361 12

Composite

❚ Idea: make abstract "component" class. ❚ Alternative 1: every component has a (possibly empty) set of components. ❚ Problem: many components have no components.

Component

Children

Paragraph Chapter ... *

slide-3
SLIDE 3

2/10/15 3

cs361 13

Composite Pattern

Component

container children:

Composite Leaf

Composite and Component have the exact same interface.

  • enumerating children
  • Component has empty

iterator

  • only Composite adds

removes children.

*

cs361 14

Two

  • des

design ign alt alter ernat nativ ives es for

  • r

Par art-of

  • of
  • 1. Component does not know what it is a part of

+ Component can be in many composites.

  • Component can be accessed only through its

composite.

  • 2. Component knows what it is a part of
  • Component can be in only one composite.

+ Component can be accessed directly.

:

cs361 15

Part-of

❚ Rules when component knows its single composite.

❙ A is a part of B if and only if B is the composite of A.

❚ Duplicating information is dangerous! ❚ Problem: how to ensure that pointers from components to composite and composite to components are consistent?

cs361 16

Ensuring Consistency

❚ The public operations on components and composites are:

❙ Composite can enumerate components. ❙ Component knows its container. ❙ Add/remove a component to/from the composite.

cs361 17

❚ The operation to add a component to a composite updates the container of the

  • component. There should be no other way

to change the container of a component.

cs361 18

addChild() in Composite

public void addChild(Component child) { ensureCapacity(); childArray[numChildren++] = child; child.container = this; }

slide-4
SLIDE 4

2/10/15 4

cs361 19

Book Example

DocumentComponent Composite Paragraph Chapter Book Section *

cs361 20

A book

❚ Book ❙ Chapter ❘ Section

  • Paragraph
  • Paragraph

❘ Section

  • Paragraph

❙ Chapter ❘ Section

  • Paragraph

cs361 21

Composite in Eclipse UI (SWT)

❚ Widget (abstract class)

❙ Control

❘ Button, Label, ProgressBar, …

❙ Composite

❘ Browser, Canvas, Table, Tree, List, …

cs361 22

Composite in Eclipse Nodes

❚ IJavaElement (interface)

❙ Leaf nodes IMember: IField, IMethod, … ❙ Composite nodes: ICompilationUnit, IPackage.....

427-21 23

When to Centralize Algorithm

Use centralized algorithm when you need to:

  • change entire algorithm at once
  • look at entire algorithm at once
  • work with only a few kinds of components
  • change algorithm often, but not add new classes
  • f components
  • change the algorithm without changing the

components (open-closed principle)

427-21 24

Visitor pattern

Visitor lets you centralize algorithm, lets you create a family of algorithms by inheritance, and lets you define a new

  • peration without changing the classes
  • f the elements on which it operates.

Major problem is that adding a new kind

  • f parse node requires adding a new

function to each visitor.

slide-5
SLIDE 5

2/10/15 5

cs361 1-25 427-21 26

Related Patterns

❚ Several patterns are often used with Interpreter/Visitor

❙ Composite - to make tree ❙ Iterator - to make traversal more abstract ❙ Template Method - to put reusable code in abstract class

427-21 27

Who is responsible for the traversal algorithm ?

The components? The Visitor? A separate iterator in the client?

427-21 28

1: The Components

If the component handles traversal, it looks like: public Object accept(Visitor visitor) { visitor.visitA(this); for (Enumeration e = children(); e.hasMoreElements) { item = (Item) e.NextElement(); item.accept(visitor); } } Otherwise, it looks like: public Object accept(Visitor visitor) {visitor.visitA(this);}

427-21 29

2: The Visitor

If the visitor handles iteration, it looks like:

public Object visitA(ComponentA c) { // do something with c for (Iterator i = c.children(); !i.isDone(); i.next()) { ((Component) i.CurrentItem()).accept(visitor); } }

Otherwise Visitor visitA just interacts with componentA.

427-21 30

3: An Iterator from Client code

If client calls iterator, it looks like:

visitor = new ConcreteVisitor. for (Iterator i = component.iterator(); !i.isDone(); i.Next()) { ((Component) i.CurrentItem()).accept(visitor); } }

Otherwise, the client looks like:

ConcreteVisitor visitor; treeRoot.accept(visitor);

slide-6
SLIDE 6

2/10/15 6

427-21 31

Visitor in Eclipse

public public abstract class abstract class ASTVisitor { public public void void visit(Assignment node) { return true; } several dozens more }

Many Eclipse tools (e.g., refactoring, code completion) walk

  • ver the AST nodes

427-21 32

Visitor in Eclipse

class Assignment {

public void void accept(ASTVisitor visitor){ boolean boolean visitChildren = visitor.visit( visitChildren = visitor.visit(this this); ); if if (visitChildren) { (visitChildren) { // visit children in normal left to right reading order acceptChild(visitor, getLeftHandSide()); acceptChild(visitor, getRightHandSide()); }

}

427-21 33

Visitor in Eclipse

❚ Visitor works best when there are no new subclasses ❚ Visitors work well for compilers. Why?

427-22 34

Template Method

❚ Problem: Some classes have a similar algorithm, but it is a little different for each class. ❚ Solution: Define the skeleton of the algorithm as a method in a superclass, deferring some steps to subclasses.

427-22 35

Template Method

❚ A template method calls abstract methods. ❚ Subclasses provide concrete implementations

  • f abstract methods.

❚ Template method in superclass calls methods in subclass ❚ Template Method separates the invariant part

  • f an algorithm from the parts that vary with

each subclass

427-22 36

In Swing’s JComponent

public void paint(Graphics g) { Graphics cg = getComponentGraphics(g); Graphics co = SwingGraphics.createSwingGraphics(cg); paintComponent(co); paintBorder(co); paintChildren(co); }

slide-7
SLIDE 7

2/10/15 7

427-22 37

Where do template methods come from?

❚ Two classes, each with a paint() method. ❚ All getComponentGraphics and then createSwingGraphics, but do different things with them. ❚ Some have border, some don’t. Some have children, some don’t. paintComponent(co); paintBorder(co); paintChildren(co);

427-22 38

Making Template Methods

❚ Given two methods with same name in different classes

❙ Mark places that are DIFFERENT ❙ Extract those places into separate methods in same classes ❙ Methods are now the same - move to superclass

427-22 39

Façade

Provide a unified interface to a set of interfaces in a

  • subsystem. Define a higher-level interface that makes

the subsystem easier to use.

Facade

427-22 40

Why Façade?

❚ Hide complexity of subsystem ❚ Make a single API instead of a set of classes ❚ Allow subsystem to change without affecting clients

427-22 41

Adapter Pattern

Intent: Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces. An adapter object will make the adaptee act like it has the target interface.

427-22 42

Adapter Pattern

Target Adapter Client Adaptee

slide-8
SLIDE 8

2/10/15 8

cs361 43

Next time

❚ Read Observer, Strategy, Command on Wikipedia