Presentation is loading. Please wait.

Presentation is loading. Please wait.

Slide 1 Design Patterns Slides adapted from various sources.

Similar presentations


Presentation on theme: "Slide 1 Design Patterns Slides adapted from various sources."— Presentation transcript:

1 Slide 1 Design Patterns Slides adapted from various sources

2 Slide 2 Outline Introduction An example: the Observer pattern History and definition of design patterns Design pattern names and categories Other Patterns: Facade, Singleton, Composite, Adapter, Bridge Pattern description Templates Summary & Benefits

3 Slide 3 Software Design – bridging the gap between requirements & Implementation What is software design? – Expressing a solution to a problem in programming language independent terms – creating a blueprint for implementation. 3 Requirements Analysis Software Design Implementation Testing Deployment Evolution Systems Engineering

4 Slide 4 Design challenges Designing software for reuse is hard; one must find: – a good problem decomposition, and the right software abstractions – a design with flexibility, modularity and elegance Designs often emerge from an iterative process (trials and many errors) Successful designs do exist – two designs are almost never identical – they exhibit some recurring characteristics The engineering perspective: can designs be described, codified or standardized? – this would short circuit the trial and error phase – produce "better" software faster

5 Slide 5 What patterns have you seen in this class?

6 Slide 6 The Model-view-controller architecture Separates the application object (model) from The way it is presented to the user (view), from The way in which the user controls it (controller). 6 User Interface or Observer Functionality Data or Subject Model View Controller change notifies query

7 Slide 7 Client-Server Architectural Pattern A K T

8 Slide 8 The seven layers of architecture * Global architecture Enterprise architecture System architecture Application architecture Macro-architecture Micro-architecture Objects * Mowbray and Malveau ORB OO architecture Frameworks Subsystem Design patterns OO programming

9 Slide 9 Goals of Design Standardization Codify good design – Distil and disseminate experience – Aid to novices and experts alike – Abstract how to think about design Give design structures explicit names – Common vocabulary – Reduced complexity – Greater expressiveness Capture and preserve design information – Articulate design decisions succinctly – Improve documentation Enhance important non-functional properties – Changeability – Reliability – Testability – Etc. © E. Gamma, R. Helm, R. Johnson, J. Vlissides and Addison-Wesley

10 Slide 10 How patterns arise Problem Context Solution Benefits Related Patterns Consequences Forces

11 Slide 11 Definition & Purpose A recurring solution to a common software problem in a context. A design pattern captures design expertise – patterns are not created from thin air, but abstracted from existing design examples Using design patterns is reuse of design expertise Studying design patterns is a way of studying how the “experts” do design Design patterns provide a vocabulary for talking about design

12 Slide 12 Is this a pattern? A=10% B=40% C=30% D=20% Data, Model or Subject A B C D ADCB Relative Percentages Y10 40 30 20 X15 35 35 15 Z10 40 30 20 A B C D Change notification Requests, modifications Observer

13 Slide 13 Observer Pattern Subject attach (Observer) detach (Observer) Notify () Observer Update() Concrete Observer Update() observerState Concrete Subject GetState() SetState() subjectState observers subject For all x in observers{ x  Update(); } observerState= subject  getState();

14 Slide 14 Class collaboration in Observer : ConcreteSubject a:ConcreteObserverb:ConcreteObserver GetState() Notify() Update() SetState() GetState() Update()

15 Slide 15 Code Example: An Observer public interface IObserver { void update(String state); } public class Observer1 implements IObserver { private String state; public String getState() { return state; } public void setState(String state) { this.state = state; } public void update(String state) { setState(state); System.out.println("Observer1 has received update signal with new state: " + getState()); }

16 Slide 16 Code Example: A Second Observer public class Observer2 implements IObserver { private String state; public String getState() { return state; } public void setState(String state) { this.state = state; } public void update(String state) { setState(state); System.out.println("Observer2 has received update signal with new state: " + getState()); }

17 Slide 17 Code Example: The Subject public class LogSubject { private List observerList = new ArrayList (); private String state; public String getState() { return state; } public void attach(IObserver observer) { observerList.add(observer); } public void detach(IObserver observer) { observerList.remove(observer); } public void setState(String state) { this.state = state; notify(); } private void notify() { for (IObserver item: observerList) { item.update(getState()); }

18 Slide 18 Code Example: The main Program public class Client { public static void main(String[] args) { LogSubject subject = new LogSubject(); IObserver ob = new Observer(); IObserver ob1 = new Observer1(); IObserver ob2 = new Observer2(); subject.attach(ob); subject.attach(ob1); subject.attach(ob2); subject.setState("state1"); subject.setState("state2"); subject.detach(ob1); subject.setState("state3"); }

19 Slide 19 CS 406: Design Patterns19 Observer Pattern: Observer code class Subject; class observer { public: virtual ~observer; protected: virtual void Update (Subject* theChangedSubject)=0; observer (); Note the support for multiple subjects. }; Abstract class defining the Observer interface.

20 Slide 20 CS 406: Design Patterns 20 Observer Pattern: Subject Code [1] class Subject { public: virtual ~Subject; protected: Subject (); virtual void Attach (observer*); virtual void Detach (observer*) ; virtual void Notify(); private: List *_observers; }; Abstract class defining the Subject interface.

21 Slide 21 CS 406: Design Patterns21 Observer Pattern: Subject Code [2] void Subject :: Attach (Observer* o){ _observers -> Append(o); } void Subject :: Detach (Observer* o){ _observers -> Remove(o); } void Subject :: Notify (){ ListIterator iter(_observers); } for ( iter.First(); !iter.IsDone(); iter.Next()) { iter.CurrentItem() -> Update(this); }

22 Slide 22 When to use the Observer Pattern? When an abstraction has two aspects: one dependent on the other. Encapsulating these aspects in separate objects allows one to vary and reuse them independently. When an update to one object requires changing others and the number of objects to be changed is not known. When an object should be able to notify others without knowing who they are. Avoid tight coupling between objects.

23 Slide 23 Observer design pattern: example 2

24 Slide 24 Observer Pattern: Consequences Abstract coupling between subject and observer. Subject has no knowledge of concrete observer classes. Support for broadcast communication. A subject need not specify the receivers; all interested objects receive the notification. Unexpected updates: Observers need not be concerned about when updates are to occur. They are not concerned about each other’s presence.

25 Slide 25 25

26 Slide 26 Observer Pattern History Software context: – Most of the work originated in SmallTalk community. – SmallTalk programming language: Object Oriented Meant for rapid prototyping Came with (what are known today as) IDE and API IDE elements were in SmallTalk! (Concrete) Precursor to modeling, frameworks and patterns!

27 Slide 27 Patterns – MVC framework SmallTalk’s user interface framework – Model - refers to data model – View – refers to external views or presentation of data. – Controller – refers to module relating reactions of view or presentation to changes in data.

28 Slide 28 The Model-view-controller architecture Separates the application object (model) from The way it is presented to the user (view), from The way in which the user controls it (controller). 28 User Interface or Observer Functionality Data or Subject Model View Controller change notifies query

29 Slide 29 Observer Pattern Model – View paradigm can be generalized: – A view is an observer – A model is an subject that is observed. – The controller may be the communication between model and view or may be incorporated in the view or model.

30 Slide 30 Pattern origins and history Writings of architect Christopher Alexander (coined this use of the term "pattern" ca. 1977-1979) – A Pattern Language in 1977 (253 patterns) Kent Beck and Ward Cunningham, Textronix, OOPSLA'87 (used Alexander's "pattern" ideas for Smalltalk GUI design) Erich Gamma, Ph. D. thesis, 1988-1991 ("Gang of Four“ Gamma, Helm, Johnson, Vlissides ("Gang of Four“ - GoF) - GoF) Design Patterns: Elements of Reusable Object-Oriented Software, 1991-1994 James Coplien, Advanced C++ Idioms book, 1989-1991 PLoP Conferences and books, 1994-present: http://hillside.net/plop/2006/http://hillside.net/plop/2006/ (“POSA book”) Buschmann, Meunier, Rohnert, Sommerland, Stal, Pattern -Oriented Software Architecture: A System of Patterns (“POSA book”)

31 Slide 31 Definition A recurring solution to a common software problem in a context. Each pattern describes a problem which occurs over and over again in our environment, 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 [Alexander]. … the abstraction from a concrete form which keeps recurring in specific non-arbitrary contexts [Riehle]. …both a thing and the instructions for making the thing [Coplien]...a literary format for capturing the wisdom and experience of expert designers, and communicating it to novices.

32 Slide 32 32

33 Slide 33 Purpose CreationalStructuralBehavioral Class  Factory Method  Adapter  Interperter Scope Object  Abstract Factory  Builder  Prototype  Singleton  Adapter  Bridge  Composite  Decorator  Facade  Flyweight  Proxy  Chain of Responsibility  Command  Iterator  Mediator  Momento  Observer  State  Strategy  Vistor Creational patterns –Abstracts the instantiation process –Dynamically create objects so that they don’t have to be instantiated directly. –Help make a system independent of how objects are represented, created and composed. Structural patterns –Concerns how groups of objects are composed into larger structures Behavioral patterns –Defines communication among objects in a given system –Provides better control of flow in a complex application Design pattern catalog - GoF

34 Slide 34 Types of software patterns Design patterns (software design) [Buschmann-POSA] – architectural (systems design) – Susbsystem design (micro-architectures) [Gamma-GoF] Analysis patterns (recurring & reusable analysis models) [Flower] Organization patterns (structure of organizations/projects) Process patterns (software process design) Other patterns…

35 Slide 35 35

36 Slide 36 Facade Pattern: Problem A C B Client Classes s1 s5 s3 s2 s4 Subsystem classes Need to communicate with

37 Slide 37 Facade Pattern: Solution A C B Client Classes S1 S5 S3 S2 S4 Subsystem classes Facade

38 Slide 38 Facade Provide unified interface to interfaces within a subsystem Shield clients from subsystem components Promote weak coupling between client and subsystem components Facade Client

39 Slide 39 Facade Pattern: Why and What? Need to provide a simple interface to many, often small, classes. But not necessarily to ALL classes of the subsystem. Facade provides a simple default view good enough for most clients. Facade decouples a subsystem from its clients. Subsystems often get complex as they evolve. A facade can be a single entry point to each subsystem level. This allows layering.

40 Slide 40 Facade Pattern: Benefits Promotes weak coupling between subsystem and its clients. Helps in layering the system. Helps eliminate circular dependencies. Shields clients from subsystem classes; reduces the number of objects that clients deal with. –Clients do not have direct access to subsystem classes.

41 Slide 41 Singleton Structure Singleton static Instance() SingletonOp() GetSingletonData() static uniqueInstance singletonData return uniqueinstance

42 Slide 42 Composite Construct part-whole hierarchy Simplify client interface to leaves/composites Easier to add new kinds of components Component Operation() Add(Component) Remove(Component) Composite Operation() Add(Component) Remove(Component) Leaf Operation() Client children 0..* For all c in children c.Operation();

43 Slide 43 Composite (2) Example: figures in a structured graphics toolkit Figure paint() translate() getBounds() CompositeFigure paint() addFigure(Figure)) removeFigure(Figure)) BasicFigure paint() View children 0..* For all c in children c.paint(); LabelFigure paint() 0..* Controller parent

44 Slide 44 Adapter pattern Delegation is used to bind an Adapter and an Adaptee Interface inheritance is use to specify the interface of the Adapter class. Target and Adaptee (usually called legacy system) pre-exist the Adapter. Target may be realized as an interface in Java. Client ClientInterface Request() LegacyClass ExistingRequest() Adapter Request() adaptee

45 Slide 45 Adapter Pattern “Convert the interface of a class into another interface clients expect.” The adapter pattern lets classes work together that couldn’t otherwise because of incompatible interfaces Used to provide a new interface to existing legacy components (Interface engineering, reengineering). Also known as a wrapper Two adapter patterns: – Class adapter: Uses multiple inheritance to adapt one interface to another – Object adapter: Uses single inheritance and delegation

46 Slide 46 Bridge Pattern Use a bridge to “decouple an abstraction from its implementation so that the two can vary independently”. (From [Gamma et al 1995]) Also know as a Handle/Body pattern. Allows different implementations of an interface to be decided upon dynamically. The bridge pattern is used to provide multiple implementations under the same interface. – Examples: Interface to a component that is incomplete, not yet known or unavailable during testing

47 Slide 47 Bridge Pattern

48 Slide 48 Adapter vs Bridge Similarities: – Both are used to hide the details of the underlying implementation. Difference: – The adapter pattern is geared towards making unrelated components work together Applied to systems after they’re designed (reengineering, interface engineering). – A bridge, on the other hand, is used up-front in a design to let abstractions and implementations vary independently. Green field engineering of an “extensible system” New “beasts” can be added to the “object zoo”, even if these are not known at analysis or system design time.

49 Slide 49 49

50 Slide 50 Pattern Description: GoF form Pattern name and classification Intent what does pattern do / when the solution works Also known as other known names of pattern (if any) Motivation the design problem / how class and object structures solve the problem Applicability situations where pattern can be applied Structure a graphical representation of classes in the pattern Participants the classes/objects participating and their responsibilities Collaborations of the participants to carry out responsibilities

51 Slide 51 Pattern Description: GoF form Consequences trade-offs, concerns Implementation hints, techniques Sample code code fragment showing possible implementation Known uses patterns found in real systems Related patterns closely related patterns

52 Slide 52 Pattern Description: Alexandrian form Name meaningful name Problem the statement of the problem Context a situation giving rise to a problem Forces a description of relevant forces and constraints Solution proven solution to the problem Examples sample applications of the pattern Resulting context (force resolution) the state of the system after pattern has been applied

53 Slide 53 Pattern Description: Alexandrian form Rationale explanation of steps or rules in the pattern Related patterns static and dynamic relationship Known use occurrence of the pattern and its application within existing system

54 Slide 54 54

55 Slide 55 Benefits of using patterns Patterns are a common design vocabulary – allows engineers to abstract a problem and talk about that abstraction in isolation from its implementation – embodies a culture; domain specific patterns increase design speed Patterns capture design expertise and allow that expertise to be communicated – promotes design reuse and avoid mistakes Improve documentation (less is needed) and understandability (patterns are described well once) Using design patterns is reuse of design expertise Studying design patterns is a way of studying how the “experts” do design Patterns do not provide exact solutions, solve all design problems or only apply to OO systems.

56 Slide 56 Patterns vs “Design” Patterns are design – But: patterns transcend the “identify classes and associations” approach to design – Instead: learn to recognize patterns in the problem space and translate to the solution Patterns can capture OO design principles within a specific domain Patterns provide structure to “design”

57 Slide 57 Patterns vs Frameworks Patterns are lower-level than frameworks Frameworks typically employ many patterns: – Factory – Strategy – Composite – Observer Done well, patterns are the “plumbing” of a framework

58 Slide 58 Patterns vs Architecture Design Patterns (GoF) represent a lower level of system structure than “architecture” (cf: seven levels of A) Patterns can be applied to architecture: – Mowbray and Malveau – Buschmann et al – Schmidt et al Architectural patterns tend to be focussed on middleware. They are good at capturing: – Concurrency – Distribution – Synchronization

59 Slide 59 More about patterns A pattern describes a recurring software structure – is abstract from concrete design elements such as problem domain, programming language – identifies classes that play a role in the solution to a problem, describes their collaborations and responsibilities – lists implementation trade-offs – patterns are not code or designs; must be instantiated/applied The software engineer is required to: – evaluate trade-offs and impact of using a pattern in the system at hand – Make design and implementation decision how best to apply the pattern, perhaps modify it slightly – Implement the pattern in code and combine it with other patterns

60 Slide 60 Six ways patterns can aid MDE? Coding patterns? 60

61 Slide 61 Online resources Pattern FAQ http://g.oswego.edu/dl/pd-FAQ/pd-FAQ.html Basic patterns http://exciton.cs.oberlin.edu/javaresources/DesignPatt erns/default.htm http://exciton.cs.oberlin.edu/javaresources/DesignPatt erns/default.htm Patterns home page http://hillside.net/patterns/

62 Slide 62 Other resources Design Patterns – Elements of Reusable Object-Oriented Software – Erich Gamma, et. Al, ISBN 0-201-63361-2 Java Design Patterns – James W. Cooper, ISBN 0-201-48539-7 Head First Design Patterns – Eric & Elisabeth Freeman (with Kathy Sierra & Bert Bates) – ISBN 0-596-00712-4

63 Slide 63 TheEnd CSC550, Devon M. Simmonds, Computer Science Department, University of North Carolina Wilmington ????????????? ?? …CSC550 … Q u e s t i o n s ?

64 Slide 64 An Example: http://en.wikipedia.org/wiki/Bridge_pattern import java.util.*; /** "Implementor" */ interface DrawingAPI { public void drawCircle(double x, double y, double radius);} /** "ConcreteImplementor" 1/2 */ class DrawingAPI1 implements DrawingAPI { public void drawCircle(double x, double y, double radius) { System.out.printf("API1.circle at %f:%f radius %f\n", x, y, radius); } /** "ConcreteImplementor" 2/2 */ class DrawingAPI2 implements DrawingAPI { public void drawCircle(double x, double y, double radius) { System.out.printf("API2.circle at %f:%f radius %f\n", x, y, radius); }

65 Slide 65 An Example … /** "Abstraction" */ interface Shape { public void draw(); public void resizeByPercentage(double pct); } /** "Refined Abstraction" */ class CircleShape implements Shape { private double x, y, radius; private DrawingAPI drawingAPI; public CircleShape(double x, double y, double radius, DrawingAPI drawingAPI) { this.x = x; this.y = y; this.radius = radius; this.drawingAPI = drawingAPI; } public void draw() { drawingAPI.drawCircle(x, y, radius); } public void resizeByPercentage(double pct) { radius *= pct; } }

66 Slide 66 An Example … /** "Client" */ class BridgePattern { public static void main(String[] args) { Shape[] shapes = new Shape[2]; shapes[0] = new CircleShape(1, 2, 3, new DrawingAPI1()); shapes[1] = new CircleShape(5, 7, 11, new DrawingAPI2()); for (Shape shape : shapes) { shape.resizeByPercentage(2.5); shape.draw(); }

67 Slide 67

68 Slide 68 68

69 Slide 69 A Scenario A=10% B=40% C=30% D=20% Data A B C D ADCB Relative Percentages Y10 40 30 20 X15 35 35 15 Z10 40 30 20 A B C D Change notification Requests, modifications Views

70 Slide 70 A Scenario Data A B C D ADCB Relative Percentages Y10 40 30 20 X15 35 35 15 Z10 40 30 20 A B C D Change notification Requests, modifications Views A10 B40 C30 D20 Need to separate presentational aspects with the data, i.e. separate views and data. Change in one view automatically reflected in other views. Also, change in the application data is reflected in all views. Defines one-to-many dependency amongst objects so that when one object changes its state, all its dependents are notified. Classes defining application data and presentation can be reused.

71 Slide 71 Is this a pattern? A=10% B=40% C=30% D=20% Data, Model or Subject A B C D ADCB Relative Percentages Y10 40 30 20 X15 35 35 15 Z10 40 30 20 A B C D Change notification Requests, modifications Observer


Download ppt "Slide 1 Design Patterns Slides adapted from various sources."

Similar presentations


Ads by Google