Design Patterns - PowerPoint PPT Presentation

1 / 77
About This Presentation
Title:

Design Patterns

Description:

E. Gamma, R. Helm, R. Johnson, and J. Vlissides, Design Patterns: Elements of ... Method Compile. void Compiler::Compile( istream& input, BytecodeStream& output) ... – PowerPoint PPT presentation

Number of Views:48
Avg rating:3.0/5.0
Slides: 78
Provided by: shyhka
Category:

less

Transcript and Presenter's Notes

Title: Design Patterns


1
Design Patterns
  • Shyh-Kang Jeng
  • Department of Electrical Engineering
  • National Taiwan University

2
Reference
  • E. Gamma, R. Helm, R. Johnson, and J. Vlissides,
    Design Patterns Elements of Reusable
    Object-Oriented Software, Addison-Wesley, 1994.
  • A. Shalloway and J. R. Trott, Design Patterns
    Explained, Addison-Wesley, 2002

3
Concept of Design Patterns
  • Each pattern describes a problem which occurs
    over and over again in our environments, and then
    describes the core of the solution to that
    problem, in such a way that you can use this
    solution a million times over, without ever doing
    it the same way twice.
  • -- Christopher Alexander,
  • A Pattern Language, 1977

4
Basics of Design Patterns
  • Design patterns are not about designs such as
    linked lists and hash tables that can be encoded
    in classes and reused as is
  • Nor are they complex, domain specific designs for
    an entire application or subsystem
  • Design patterns are descriptions of communicating
    objects and classes that are customized to solve
    a general design problem in a particular context
  • Encapsulate the concept that varies

5
Elements of a Pattern
  • Pattern Name
  • Problem
  • Solution
  • Consequence

6
Design Pattern Space
7
Model-View-Controller
D. Collins, Designing Object-Oriented User
Interfaces,
Benjamin/Cummings, 1995.
8
Presentations of Data
9
Observer Pattern
  • Define a one-to-many dependency between objects
    so that when one object changes state, all its
    dependents are notified and updated automatically

10
Observer Pattern
11
Observer Pattern
12
Class Observer
  • class Subject
  • class Observer
  • public
  • virtual Observer( )
  • virtual void Update(
  • Subject theChangedSubject) 0
  • protected
  • Observer( )

13
Class Subject
  • class Subject
  • public
  • virtual Subject( )
  • virtual void Attach(Observer)
  • virtual void Detach(Observer)
  • virtual void Notify( )
  • protected
  • Subject( )
  • private
  • ListltObservergt observers

14
Methods in Subject
  • void SubjectAttach(Observer o)
  • observers-gtAppend(o)
  • void SubjectNotify( )
  • ListIteratorltObservergt i(observers)
  • for(i.First( ) !i.IsDone( ) i.Next( ))
  • i.CurrentItem( )-gtUpdate(this)

15
Document-Application Application Framework
16
Template Method Pattern
  • Define the skeleton of an algorithm in an
    operation, deferring some steps to subclasses
  • Let subclasses redefine certain steps of an
    algorithm without changing the algorithms
    structure
  • Hook operations

17
Template Method Pattern
18
Methods in View
  • void ViewDisplay( )
  • SetFocus( )
  • DoDisplay( )
  • ResetFocus( )
  • void ViewDoDisplay( )
  • void MyViewDoDisplay( )

19
Compiler System
20
Façade Pattern
  • Provide a unified interface to a set of
    interfaces in a subsystem
  • Define a higher-level interface that makes the
    subsystems easier to use
  • Not prevent applications from using subsystem
    classes if we need to
  • Can choose between ease of use and generality

21
Façade Pattern
22
Class Compiler
  • class Compiler
  • public
  • Compiler( )
  • virtual void Compile(
  • istream, BytecodeStream)

23
Method Compile
  • void CompilerCompile(
  • istream input,
  • BytecodeStream output)
  • Scanner scanner(input)
  • ProgramNodeBuilder builder
  • Parser parser
  • parser.parse(scanner, builder)
  • RISCCodeGenerator generator(output)
  • ProgramNode parseTree builder.GetRootNode(
    )
  • parseTree-gtTraverse(generator)

24
Font Dialog Box
25
Mediator Pattern
  • Define an object that encapsulates how a set of
    objects interact
  • Promote loose coupling by keeping objects from
    referring to each other explicitly
  • Let the client vary interactions of objects
    independently
  • Centralize control

26
Mediator Pattern
27
Mediator Pattern
28
Mediator Pattern
29
Class DialogDirector
  • class DialogDirector
  • public
  • virtual DialogDirector( )
  • virtual void ShowDialog( )
  • virtual void WidgetChanged(Widget) 0
  • protected
  • DialogDirector( )
  • virtual void CreateWidgets( ) 0

30
Class Widget
  • class Widget
  • public
  • Widget(DialogDirector)
  • virtual void Changed( )
  • virtual void HandleMouse(
  • MouseEvent event)
  • private
  • DialogDirector director

31
Class ListBox
  • class ListBox public Widget
  • public
  • ListBox(DialogDirector)
  • virtual string GetSelection( )
  • virtual void SetList(
  • Listltstringgt listItems)
  • virtual void HandleMouse(
  • MouseEvent event)

32
Class FontDialogDirector
  • class FontDialogDirector
  • public DialogDirector
  • public
  • FontDialogDirector( )
  • virtual FontDialogDirector( )
  • virtual void WidgetChanged(Widget)
  • protected
  • virtual void CreateWidgets( )
  • private
  • ListBox fontList

33
Singleton Pattern
  • Ensure a class only has one instance, and provide
    a global point of access to it
  • Provide controlled access to sole instance
  • Reduce name space

34
Singleton Pattern
35
Class MazeFactory
  • class MazeFactory
  • public
  • static MazeFactory Instance( )
  • protected
  • MazeFactory( )
  • private
  • static MazeFactory instance

36
Invoking Singleton Instance
  • MazeFactory
  • MazeFactoryinstance NULL
  • MazeFactory MazeFactoryInstance( )
  • if( instance NULL )
  • instance new MazeFactory
  • return instance

37
Subclass of a Singleton
  • class BombedMazeFactory
  • public MazeFactory

38
Invoking Singleton Instance
  • MazeFactory MazeFactoryInstance( )
  • if( instance NULL )
  • const char mazeStyle
  • getenv(MAZESTYLE)
  • if(strcmp(mazeStyle,bombed)0)
  • instance new BomedMazeFactory
  • else if
  • else
  • instance new MazeFactory
  • return instance

39
Class Singleton
  • class Singleton
  • public
  • static void Register( char name,
  • Singleton)
  • static Singleton Instance()
  • protected
  • static Singleton Lookup(
  • const char name)
  • private
  • static Singleton instance
  • static ListltNameSingletonPairgt registry

40
Method Instance
  • Singleton SingletonInstance()
  • if( instance NULL )
  • const char singletonName
  • getenv(SINGLETON)
  • instance
  • Lookup( singletonName )
  • return instance

41
Register a Singleton Object
  • class MySingleton public Singleton
  • Static MySingleton theSingleton
  • MySingletonMySingleton()
  • SingletonRegister(MySingleton,
  • this)

42
TCP Connection
43
State Pattern
  • Allow an object to alter its behavior when its
    internal state changes
  • Localize state-specific behavior and partition
    behavior for different states
  • Make state transitions explicit
  • State objects can be shared

44
State Pattern
45
Class TCPConnection
  • class TCPState
  • class TCPConnection
  • public
  • TCPConnection( )
  • void ActiveOpen( )
  • private
  • friend class TCPState
  • void ChangeState(TCPState)
  • private
  • TCPState state

46
Class TCPState
  • class TCPState
  • public
  • virtual void ActiveOpen(TCPConnection)
  • virtual void Synchronize(TCPConnection)
  • virtual void Acknowledge(TCPConnection)
  • virtual void Send(TCPConnection)
  • protected
  • void ChangeState(
  • TCPConnection,TCPState)

47
State Classes
  • class TCPListen public TCPState
  • public
  • static TCPState Instance( )
  • virtual void Send(TCPConnection)
  • class TCPClosed public TCPState
  • public
  • static TCPState Instance( )
  • virtual void ActiveOpen(TCPConnection)

48
Drawing Editor
49
Adapter Pattern
  • Convert the interface of a class into another
    interface clients expect
  • Allow classes work together that could not
    otherwise because of incompatible interfaces
  • Clients call operations on an Adapter instance.
    In turn, the adapter calls Adaptee operations
    that carry out the request

50
Adapter Pattern
51
Class Shape
  • class Shape
  • public
  • Shape( )
  • virtual void BoundingBox (
  • Point bottomLeft,
  • Point topRight ) const
  • virtual Manipulator CreateManipulator( )
    const

52
Class TextView
  • class TextView
  • public
  • TextView( )
  • void GetOrigin(Coord x, Coord y) const
  • void GetExtent(Coord width,
  • Coord height) const
  • virtual bool IsEmpty( ) const

53
Class TextShape
  • class TextShape public Shape
  • public
  • TextShape(TextView)
  • virtual void BoundingBox(
  • Point bottomLeft,
  • Point topRight ) const
  • virtual bool IsEmpty( ) const
  • virtual Manipulator CreateManipulator( )
    const
  • private
  • TextView text

54
Method BoundingBox
  • void TextShapeBoundingBox(
  • Point bottomLeft,
  • Point topRight ) const
  • Coord bottom, left, width, height
  • text-gtGetOrigin(bottom, left)
  • text-gtGetExtent(width, height)
  • bottomLeft Point(bottom, left)
  • topRight Point(bottomheight, leftwidth)

55
Exercise (1)
  • Some library classes like DirectSound (actually a
    COM component) in DirectX can be used to play
    sound directly from a memory buffer. However, if
    we want to play a music of MIDI or WAVE format,
    we have to adapt those library classes to accept
    MIDI or WAVE format. Try to develop such adapter
    classes, assuming that you want to use a method
    play() in your own class, say, CMIDI or CWave, to

56
Exercise (2)
  • play a piece of MIDI or WAVE music. In the
    play() method, you may have to use methods
    Initialize() and CreateSoundBuffer() in class
    DirectSound and methods Play() in class
    DirectSoundBuffer. Note that this is an
    over-simplified description, you are free to add
    anything you think existent in those two library
    classes. Of course, if you are interested, you
    may get some related books for details.

57
Graphics
58
Proxy Pattern
  • Provide a surrogate or placeholder for another
    object to control access to it
  • Forward requests to real subject when
    appropriate, depending on the kind of proxy
  • Remote proxy can hide the fact that an object
    resides in a different address space
  • Virtual proxy can perform optimizations such as
    creating an object on demand

59
Proxy Pattern
60
Class Graphic
  • class Graphic
  • public
  • virtual Graphic( )
  • virtual void Draw( ) 0
  • virtual void HandleMouse(
  • Event event)0
  • virtual
  • const Point GetExtent( ) 0
  • virtual void Load(istream from) 0
  • virtual void Save(ostream to)
  • 0
  • protected
  • Graphic( )

61
Class Image
  • class Image public Graphic
  • public
  • Image(string file)
  • virtual Image( )
  • virtual void Draw(
  • const Point at)
  • virtual void HandleMouse(
  • Event event)
  • virtual const Point GetExtent( )
  • virtual void Load(istream from)
  • virtual void Save(ostream to)

62
Class ImageProxy
  • class ImageProxy public Graphic
  • public
  • ImageProxy(string file)
  • virtual ImageProxy( )
  • protected
  • Image GetImage( )
  • private
  • Image image
  • Point extent
  • string fileName

63
Method GetImage
  • ImageProxyImageProxy(
  • string fileName)
  • fileName fileName
  • extent PointZero
  • image NULL
  • Image ImageProxyGetImage( )
  • if( image NULL )
  • image new Image(fileName)
  • return image

64
Methods in ImageProxy
  • void ImageProxyDraw(
  • const Point at)
  • GetImage( )-gtDraw(at)
  • void ImageProxyHandleMouse(
  • Event event ) GetImage( )
  • -gtHandleMouse(event)
  • void ImageProxySave(ostream to)
  • to ltlt extent ltlt fileName
  • void ImageProxyLoad(
  • ifstream from)
  • from gtgt extent gtgt fileName

65
Invoking ImageProxy
  • class TextDocument
  • public
  • TextDocument( )
  • Void Insert(Graphic)
  • TextDocument text
  • new TextDocument
  • text-gtInsert( new ImageProxy(anImageFileName))

66
Creating Mazes
67
Creating Mazes
  • Maze MazeGameCreateMaze( )
  • Maze aMaze new Maze
  • Room r1 new Room(1)
  • Room r2 new Room(2)
  • Door theDoor new Door(
  • r1, r2 )
  • aMaze-gtAddRoom( r1 )
  • aMaze-gtAddRoom( r2 )
  • Set sides for each room
  • return aMaze

68
Builder Pattern
  • Separate the construction of a complex object
    from its representation so that the same
    construction process can create different
    representations
  • The algorithm for creating a complex object
    should be independent of the parts that make up
    the object and how they are assembled
  • Gives finer control over the construction process

69
Builder Pattern
70
Builder Pattern
71
Class MazeBuilder
  • class MazeBuilder
  • public
  • virtual void BuildMaze( )
  • virtual void BuildRoom( int room )
  • virtual void BuildDoor(
  • int roomFrom, int roomTo )
  • virtual Maze GetMaze( )
  • return NULL
  • protected
  • MazeBuilder( )

72
Method CreateMaze
  • Maze MazeGameCreateMaze(
  • MazeBuilder builder )
  • builder.BuildMaze( )
  • builder.BuildRoom(1)
  • builder.BuildRoom(2)
  • builder.BuildDoor(1, 2)
  • return builder.GetMaze( )

73
Class StandardMazeBuilder
  • class StandardMazeBuilder
  • public MazeBuilder
  • public
  • StandardMazeBuilder( )
  • virtual void BuildMaze( )
  • virtual void BuildRoom(
  • int room )
  • virtual void BuildDoor(
  • int roomFrom, int roomTo )
  • virtual Maze GetMaze( )
  • private
  • Maze currentMaze

74
Class CountingMazeBuilder
  • class CountingMazeBuilder
  • public MazeBuilder
  • public
  • CountingMazeBuilder( )
  • virtual void BuildMaze( )
  • virtual void BuildRoom(
  • int room )
  • virtual void BuildDoor(
  • int roomFrom, int roomTo )
  • virtual Maze GetCounts( )
  • private
  • int doors, rooms

75
Method BuildRoom
  • CountingMazeBuilder
  • CountingMazeBuilder()
  • rooms 0
  • doors 0
  • void CountingMazeBuilderBuildRoom(
  • int )
  • rooms

76
Invoking MazeBuilder
  • Maze maze
  • MazeGame game
  • StandardMazeBuilder builder1
  • game.CreateMaze( builder1 )
  • maze builder1.GetMaze()
  • int rooms, doors
  • CountingMazeBuilder builder2
  • game.CreateMaze( builder2 )
  • builder2.GetCounts( rooms, doors )

77
Exercise
  • Suppose that you want to create x-y plots, which
    can be a linear plot, a semi-log plot, or a
    full-log plot. Write classes LinearPlotBuilder,
    SemiLogPlotBuilder, and FullLogPlotBuilder to
    build those three kinds of plots. Note that an
    x-y plot can be obtained via building the
    horizontal axis, the vertical axis, and the
    curves. Prepare a test program to test these
    classes. No much details required.
Write a Comment
User Comments (0)
About PowerShow.com