design patterns today: intro to topic designpatterns.f12.ppt cs 121 “ordering chaos” “mike”...

Post on 18-Dec-2015

212 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Design PatternsDesign Patterns

Today:Today: Intro to Topic http://www.soapatterns.org

designpatterns.f12.ppt

CS 121“Ordering Chaos”

“Mike” Michael A. Erlinger

– 2 – CS 121

Due This WeekDue This Week

• Finished ProposalFinished Proposal

• PrototypePrototype

• Review of Phase 1Review of Phase 1

• 22ndnd Floor – who is using what? Floor – who is using what?

– 3 – CS 121

DesignDesign

PracticesPractices

PrinciplesPrinciples

PatternsPatterns

What are the characteristics of good design?

What are good solutions to common design problems?

How do we go about design and what do we produce?

LAST TIME

TODAY: Design patterns

– 4 – CS 121

GoalsGoals

1.1. Make it easy to buildMake it easy to build

2.2. Make it easy to testMake it easy to test

3.3. Make it easy to maintainMake it easy to maintain

4.4. Make it easy to changeMake it easy to change

SIMPLE

FLEXIBLE

INTUITIVE

– 5 – CS 121

Design principlesDesign principlesDonDon’’t repeat yourself (D.R.Y)t repeat yourself (D.R.Y)

Use real world objectsUse real world objects

Single responsibility principleSingle responsibility principle

Encapsulate variationEncapsulate variation

High cohesion/low couplingHigh cohesion/low coupling

Program to an interface, not an implementationProgram to an interface, not an implementation

Law of Demeter (talk only to your friends)Law of Demeter (talk only to your friends)

Favor composition over inheritanceFavor composition over inheritance

Open-closed principleOpen-closed principle

Liskov Substitution PrincipleLiskov Substitution Principle

– 6 – CS 121

Design PatternsDesign Patterns

Good solution to common problemGood solution to common problem

Also illustrates good design principles in action

An area of research in both hardware and software for years

– 7 – CS 121

Design PatternsDesign Patterns

The simplest way to describe a pattern is that it The simplest way to describe a pattern is that it provides a proven solution to a common provides a proven solution to a common problem individually documented in a problem individually documented in a consistent format and usually as part of a consistent format and usually as part of a larger collection. larger collection.

– 8 – CS 121

Design Patterns are helpful because they:Design Patterns are helpful because they:

••represent field-tested solutions to common design problemsrepresent field-tested solutions to common design problems

••organize design intelligence into a standardized and easily "referencable" formatorganize design intelligence into a standardized and easily "referencable" format

••are generally repeatable by most IT professionals involved with designare generally repeatable by most IT professionals involved with design

••can be used to ensure consistency in how systems are designed and builtcan be used to ensure consistency in how systems are designed and built

••can become the basis for design standardscan become the basis for design standards

••are usually flexible and optional (and openly document the impacts of their are usually flexible and optional (and openly document the impacts of their application and even suggest alternative approaches)application and even suggest alternative approaches)

••can be used as educational aids by documenting specific aspects of system design can be used as educational aids by documenting specific aspects of system design (regardless of whether they are applied)(regardless of whether they are applied)

••can sometimes be applied prior and subsequent to the implementation of a systemcan sometimes be applied prior and subsequent to the implementation of a system

••can be supported via the application of other design patterns that are part of the can be supported via the application of other design patterns that are part of the same collectionsame collection

••enrich the vocabulary of a given IT field because each pattern is given a meaningful enrich the vocabulary of a given IT field because each pattern is given a meaningful namename

– 9 – CS 121

Problem: I want a value in multiple places?....MikeProblem: I want a value in multiple places?....Mike

CLASS: Ball

double gravity 32.1Private:

CLASS: Enemy

double gravity 32.1Private:

D.R.Y.!

– 10 – CS 121

How about this?How about this?

Global double gravity 3.21Global double gravity 3.21

– 11 – CS 121

Why not use globals?Why not use globals?

A.A. They make code hard to understand.They make code hard to understand.

B.B. They make code hard to debug.They make code hard to debug.

C.C. They make code hard to modify.They make code hard to modify.

– 12 – CS 121

AnswerAnswer

All of the above.

– 13 – CS 121

Solution: Singleton PatternSolution: Singleton Pattern

Problem: Ensure a class has only one instance and Problem: Ensure a class has only one instance and provide a global point of access to that instance.provide a global point of access to that instance.

Way to control Global VariablesWay to control Global Variables

– 14 – CS 121

Problem: I want … Lihue2Problem: I want … Lihue2

I want a 2D graphics library that supports the following I want a 2D graphics library that supports the following functions for triangles:functions for triangles: set color to r,g,b translate vertices by dx, dy rotate degrees about the origin draw

– 15 – CS 121

What I HaveWhat I Have

I have a 3D graphics library with a triangle class with the following I have a 3D graphics library with a triangle class with the following interfaceinterface triangle() triangle(v1x, v1y, v1z, v2x, v2y, v2z, v3x, v3y, v3z) ~triangle() set color(r, g, b) rotate(vector, angle) translate(dx, dy, dz) scale(sx, sy, sz) draw() flip(planeA, planeB, planeC, planeD) texture(textureMap) standardize()

– 16 – CS 121

How About: Just use the 3d classHow About: Just use the 3d class

Constructor:Constructor:

triangle t(v1x, v1y, 0, v2x, v2y, 0, v3x, v3y, 0)triangle t(v1x, v1y, 0, v2x, v2y, 0, v3x, v3y, 0)

Rotate:Rotate:

t.rotate(<0,0,1>,alpha)t.rotate(<0,0,1>,alpha)

Interface Segregation PrincipleThe dependency of one class to another one should depend on the smallest possible interface.Liskov principle

– 17 – CS 121

Solution: Façade PatternSolution: Façade Pattern

Problem:Problem:

You need to use a subset of a complex You need to use a subset of a complex system or you need to interact with the system or you need to interact with the system in a particular way.system in a particular way.

– 18 – CS 121

Problem: What I want… Linue1Problem: What I want… Linue1

I want a physics engine that (among other things) I want a physics engine that (among other things) detects collisions:detects collisions:

cCollision cPhysicsEngine::detectCollision(cPath p, cTriangles t)cCollision cPhysicsEngine::detectCollision(cPath p, cTriangles t)

I have a fast collision detection algorithm and a slower, more robust algorithm.

– 19 – CS 121

cPhysicsEngine

cPhysicsFast

How about this?

cPhysicsSlow

In the future I may want to use a super slow algorithm.

– 20 – CS 121

Solution: Strategy Design PatternSolution: Strategy Design Pattern

Problem: Want to be able to swap the algorithm used Problem: Want to be able to swap the algorithm used in an application.in an application.

– 21 – CS 121

cPhysicsEngine cDetectCollision

cDetectCollisionFast

Strategy Design Pattern

cDetectCollisionSlow

encapsulate change single responsibility open-closed principleFavor composition overinheritance

– 22 – CS 121

Problem: I want … SycamoreProblem: I want … Sycamore

I am developing software that (among other I am developing software that (among other things) displays geometric primitivesthings) displays geometric primitives

Initially I only need to support linesInitially I only need to support lines

In the future I may need to add spheres, In the future I may need to add spheres, triangles, and squarestriangles, and squares

Rather than reinvent the wheel, I am going to Rather than reinvent the wheel, I am going to use an existing program.use an existing program.

Actually, I really want the option of choosing at Actually, I really want the option of choosing at run time between two different drawing run time between two different drawing programs, one that is better at low programs, one that is better at low resolutions and one that is better at high resolutions and one that is better at high resolutionsresolutions

– 23 – CS 121

…current design…current design

shape

line

draw()

– 24 – CS 121

Drawing APIsDrawing APIs

Package 1:Package 1:

drawLine(x1, y1, x2, y2)drawLine(x1, y1, x2, y2)

Package 2: Package 2:

drawALine(x1, x2, y1, y2)drawALine(x1, x2, y1, y2)

Notice difference inParameter order

– 25 – CS 121

What about…What about…

line.draw() {line.draw() {

if (resolution == high)if (resolution == high)

drawLine(v1.x, v1.y, v2.x, v2.y)drawLine(v1.x, v1.y, v2.x, v2.y)

elseelse

drawALine(v1.x, v2.x, v1.y, v2.y)drawALine(v1.x, v2.x, v1.y, v2.y)

}}

– 26 – CS 121

Comments:Comments:

AdvantagesAdvantages simple to implement simple to understand

DisadvantagesDisadvantages is knowing about

resolution really a responsibility of shape?

D.R.Y.

– 27 – CS 121

What aboutWhat about

line

lineDP1 lineDP2

– 28 – CS 121

Comments:Comments:

AdvantagesAdvantages simple to implement simple to understand

DisadvantagesDisadvantages as additional

shapes and drawing programs are added the number of classes becomes LARGE

– 29 – CS 121

Solution: Bridge Design PatternSolution: Bridge Design Pattern

Problem: Want to support multiple implementation that Problem: Want to support multiple implementation that have different interfaces in an extensible way.have different interfaces in an extensible way.

– 30 – CS 121

Shape

TriangleLine

Drawer

Low ResHi Res

Solution: Bridge Design Patterndefines the interfaceshapes use to draw

“adapters” for specificdrawing interfaces

– 31 – CS 121

Bridge Pattern vs. Strategy PatternBridge Pattern vs. Strategy Pattern

Shape Drawer

Low ResHi Res

cPhysicsEngine cDetectCollision

cDetectCollisionFastcDetectCollisionSlow

Different intents: • bridge allows implementation to

vary and includes adapters• strategy allows algorithms (behavior) to vary

DP hi res DP hi res

– 32 – CS 121

Problem: I want …. Rio de ValleProblem: I want …. Rio de Valle

I am building a drawing program. The user I am building a drawing program. The user enters keystrokes to change modes (Add, enters keystrokes to change modes (Add, Delete, Move) and mouse input that is Delete, Move) and mouse input that is interpreted based on the current mode.interpreted based on the current mode.

– 33 – CS 121

DrawerprocessKey

processMouse

DeleteModeDrawer

AddModeDrawer

MoveModeDrawer

How about this?

What are its disadvantages?

– 34 – CS 121

DrawerprocessKey

processMouse

ModeprocessMouse

DeleteAdd Move

State Design Pattern

1

supports open-closed and single responsibility principles

– 35 – CS 121

DrawerprocessKey

processMouse

ModeprocessMouse

DeleteAdd Move

State Design Pattern

1

ModeManagerprocessKey

1 1 1

1

Mode mgr. returns pointer to correct mode

– 36 – CS 121

Solution: State Design PatternSolution: State Design Pattern

Problem: want to allow an object to alter its behavior Problem: want to allow an object to alter its behavior when its internal state changeswhen its internal state changes

– 37 – CS 121

State Pattern vs. Strategy PatternState Pattern vs. Strategy Pattern

DrawerprocessKey

processMouse

ModeprocessMouse

DeleteAdd Move

1

ModeManagerprocessKey

1 1 1

1

cPhysicsEngine cDetectCollision

cDetectCollisionFastcDetectCollisionSlow

Different intents: • state allows behaviors to vary dynamically• strategy typically used when algorithm is selected at start

– 38 – CS 121

Problem…. Continued…MikeProblem…. Continued…Mike

I also want to support I also want to support ““UndoUndo””

Help!Help!

– 39 – CS 121

Command

MouseKey Menu

Solution: Command Design PatternSolution: Command Design Pattern

– 40 – CS 121

Command Design PatternCommand Design Pattern

Encapsulate a request as an object to permit logging, Encapsulate a request as an object to permit logging, queuing, un-doing etc.queuing, un-doing etc.

– 41 – CS 121

Problem: I wantProblem: I want

I want a 2D drawing program that supports I want a 2D drawing program that supports triangle and lines triangle and lines

I want to be able to add, delete, draw, and move I want to be able to add, delete, draw, and move primitives.primitives.

I want to be also want to be able to group I want to be also want to be able to group primitives into a primitives into a ““widgetwidget”” and treat the and treat the widget as a primitive.widget as a primitive.

I want to be able to add and delete primitives I want to be able to add and delete primitives from a widgetfrom a widget

– 42 – CS 121

What about….What about….

Widget Shape*

Triangle Line

What is the difference between a triangle and a widget holding a triangle?

– 43 – CS 121

Composite Design PatternComposite Design Pattern

Widget

Shape*

Triangle Line

– 44 – CS 121

Observer Design PatternObserver Design Pattern

– 45 – CS 121

Observer Design PatternObserver Design Pattern

– 46 – CS 121

Other design patternsOther design patterns

wikipedia!

– 47 – CS 121

Why Design Patterns?Why Design Patterns?

When you have a thorny problem and you think When you have a thorny problem and you think someone must have run into it before … think design someone must have run into it before … think design patternspatterns

– 48 – CS 121

The EndThe End

– 49 – CS 121

SolutionSolution

Triangle2D Triangle3D

implements the 2d triangle interface

top related