Presentation is loading. Please wait.

Presentation is loading. Please wait.

Design Patterns Slides adapted from various sources.

Similar presentations


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

1 Design Patterns Slides adapted from various sources

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 Requirements Analysis
Software Design – bridging the gap between requirements & Implementation Software Design Requirements Analysis Implementation Systems Engineering Testing Deployment Evolution What is software design? Expressing a solution to a problem in programming language independent terms – creating a blueprint for implementation.

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 Design Rules for Architecting system characteristics
Performance Localize critical operations and minimize communications. Use large rather than fine-grain components. Security Use a layered architecture with critical assets in the inner layers. Safety Localize safety-critical features in a small number of sub-systems. Availability Include redundant components and mechanisms for fault tolerance. Maintainability Use fine-grain, replaceable components.

6 Design Rules for General System Design
Coupling Design and architect software so as to minimize the coupling of software components. Cohesion Design and architect software so as to maximize the cohesion of software components. Low coupling – high cohesion.

7 Design challenges The engineering perspective:
Can designs be described, codified and standardized? What would such a standard look like? Standardization would short circuit the trial and error phase of design and potentially produce better software.

8 Standardizing Design Motivating Example 8

9 A Scenario Views A D C B Y 10 40 30 20 X 15 35 35 15 Z 10 40 30 20
Relative Percentages Y X Z A B C D A B C D A=10% B=40% C=30% D=20% Change notification Requests, modifications Data

10 A Scenario Application Data Rules/Principles
B C D Relative Percentages Y X Z A B C D Change notification Requests, modifications Views A 10 B 40 C 30 D 20 Application Data Rules/Principles Separate presentational aspects from 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. Define one-to-many dependency amongst objects so that when one object changes its state, all its dependents are notified. Support reuse of classes defining application data and presentation.

11 Is this a pattern of design?
Observer A D C B Relative Percentages Y X Z A B C D A B C D A=10% B=40% C=30% D=20% Change notification Requests, modifications Data, Model or Subject

12 The Model-view-controller architecture
Data or Subject Functionality Model change Controller notifies query change View User Interface or Observer 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). 12

13 What other patterns have you seen in this class?

14 Architectural Patterns to Date
K T

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

16 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

17 How design patterns arise
Problem Context Forces Solution Benefits Consequences Related Patterns

18 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

19 Is this a design pattern?
Observer A D C B Relative Percentages Y X Z A B C D A B C D A=10% B=40% C=30% D=20% Change notification Requests, modifications Data, Model or Subject

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

21 Class collaboration in Observer
:ConcreteSubject a:ConcreteObserver b:ConcreteObserver SetState() Notify() Update() GetState() Update() GetState()

22 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());

23 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());

24 Code Example: The Subject
public class LogSubject { private List<IObserver> observerList = new ArrayList<IObserver>(); 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()); } }

25 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"); }

26 Code Example 2

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

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

29 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<Observer*> iter(_observers); for ( iter.First(); !iter.IsDone(); iter.Next()) { iter.CurrentItem() -> Update(this); } } CS 406: Design Patterns

30 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.

31 Observer Pattern: Benefits
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.

32 History & Definition 32

33 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!

34 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.

35 The Model-view-controller architecture
Data or Subject Functionality Model change Controller notifies query change View User Interface or Observer 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). 35

36 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.

37 Pattern origins and history
Writings of architect Christopher Alexander (coined this use of the term "pattern" ca ) 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, Gamma, Helm, Johnson, Vlissides ("Gang of Four“ - GoF) Design Patterns: Elements of Reusable Object-Oriented Software, James Coplien, Advanced C++ Idioms book, PLoP Conferences and books, 1994-present: Buschmann, Meunier, Rohnert, Sommerland, Stal, Pattern -Oriented Software Architecture: A System of Patterns (“POSA book”) As mentioned before, the current use of the term "pattern" is derived from the writings of the architect Christopher Alexander who has written several books on the topic as it relates to urban planning and building architecture (list of books). Patterns in software first became popular with the wide acceptance of the book Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (frequently referred to as the Gang of Four or just GoF). Other recent books that have helped popularize patterns are: Pattern-Oriented Software Architecture: A System of Patterns (also called the POSA book) by Frank Buschmann, Regine Meunier, Hans Rohnert, Peter Sommerlad, and Michael Stal (sometimes called the Siemens Gang of Five or just GoV); and the books Pattern Languages of Program Design and Pattern Languages of Program Design 2, which are selected papers from the first and second conferences on Patterns Languages of Program Design (PLoP or PLoPD). Many of these books are part of the Software Patterns Series from Addison-Wesley.

38 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. It is unavoidable to mention what Alexander says about patterns, since the origin of design patterns lies in work done by him in late 70is. Although Alexander was talking about patterns in buildings, the core of patterns in object-oriented design and building is a solution to a problem in a context. In "Understanding and Using Patterns in Software Development", Dirk Riehle and Heinz Zullighoven give a nice definition of the term "pattern" which is very broadly applicable. Coplein in his paper “Software Design Patterns: Common questions and Answers” refers to patterns as both the thing and the instructions for making the thing. Basically, pattern can be viewed as a particular prose form of recording design information such that designs which have worked well in the past can be applied again in similar situations in the future. (Beck, Coplien - “Industrial experience with design patterns”

39 Design Pattern Names & Categories
39

40 Design pattern catalog - GoF
Purpose Creational Structural Behavioral Class Factory Method Adapter Interperter Scope Object Abstract Factory Builder Prototype Singleton Bridge Composite Decorator Facade Flyweight Proxy Chain of Responsibility Command Iterator Mediator Momento Observer State Strategy Vistor In Gamma’s book, patterns are classified by two criteria. First is Purpose, which reflects what pattern does. Patterns can have either creational, structural, or behavioral purpose. Creational patterns concern the process of object creation. Structural patterns deal with the composition of classes or objects. Behavioral patterns characterize the ways in which classes or objects interact and distribute responsibility. The second criterion is scope, which specifies whether the pattern applies primarly on classes or objects. Class patterns deal with relationships between classes and their sub-classes. These relationships are established through inheritance, so they are static (fixed at compile time). Object patterns deal with object relationships, which can be changed at run-time and are more dynamic. (petterns labeled as class patterns are those that focus on class relationships. Structural patterns Concerns how groups of objects are composed into larger structures 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. Behavioral patterns Defines communication among objects in a given system Provides better control of flow in a complex application

41 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… Much of the initial patterns focus in the software community has been on design patterns. The patterns in the [GoF] book are object-oriented design patterns. However, there are many other kinds of software patterns besides design patterns. For example, Martin Fowler has written a book of Analysis Patterns. Patterns cover all aspects of software engineering including: development organization, software process, project planning, requirements engineering, and software configuration, management (just to name a few). Presently however, design patterns still seem to be the most popular (though organization patterns seem to be gaining momentum). ---- The difference between these three kinds of design patterns are in their corresponding levels of abstraction and detail. Architectural patterns are high-level strategies that concern large-scale components and the global properties and mechanisms of a system. They have wide-sweeping implications which affect the overall skeletal structure and organization of a software system. Design patterns are medium-scale tactics that flesh out some of the structure and behavior of entities and their relationships. They do not influence overall system structure, but instead define micro-architectures of subsystems and components. Idioms are paradigm-specific and language-specific programming techniques that fill in low-level internal or external details of a component's structure or behavior.

42 Other Design Pattern Examples 42

43 Facade Pattern: Problem
Client Classes Need to communicate with s1 s5 s3 s2 s4 Subsystem classes

44 Facade Pattern: Solution
B Client Classes Facade S1 S5 S3 S2 S4 Subsystem classes

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

46 Facade Pattern: Why and What?
Subsystems often get complex as they evolve. 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. A facade can be a single entry point to each subsystem level. This allows layering.

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

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

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

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

51 Adapter pattern ClientInterface LegacyClass Client Adapter Request()
ExistingRequest() Adapter adaptee

52 Adapter pattern Delegation is used to bind an Adapter and an Adaptee
target adaptee 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.

53 Using the Adapter Pattern
interface IBank { public void deposit(double amount); public double withdraw(double amount); public void transfer(Account from, Account to, double amount); public double getBalance(); public Account getAccount(int accountNumber); } Original Environment class BankClass implements IBank { //… } class StockClass implements IBank { BankClass b = new BankClass(); StockClass obj = new StockClass(); obj.deposit(b.withdraw(200)); obj.transfer(b.getAccount(), b.getAccount(), 400);

54 Adapting to a new environment
class BankClass implements IBank { //… } class StockClass implements IBank { Original Environment class BankClass implements IBank { //… } class StockClass implements IStock { New Environment

55 Adapting to a new environment: will the old code work?
interface IBank { public void deposit(double amount); public double withdraw(double amount); public void transfer(Account from, Account to, double amount); public double getBalance(); public Account getAccount(int accountNumber); } interface IStock { public boolean deposit(float amount); public void withdraw(double amount); public boolean transfer(Account from, Account to, Money m); BankClass b = new BankClass(); StockClass obj = new StockClass(); obj.deposit(b.withdraw(200)); obj.transfer(b.getAccount(), b.getAccount(), 400);

56 Will the old code work? So casting will do in this case.
class BankClass implements IBank { public static void main(String[] args) { } BankClass b = new BankClass(); StockClass obj = new StockClass(); obj.deposit(b.withdraw(200)); BankClass b = new BankClass(); StockClass obj = new StockClass(); obj.deposit((float)b.withdraw(200)); So casting will do in this case.

57 Create an Adapter class
Will the old code work? class BankClass implements IBank { public static void main(String[] args) { } but the Client code has to change… BankClass b = new BankClass(); StockClass obj = new StockClass(); obj.transfer(b.getAccount(12345), b.getAccount(45567), 400); public class StockClassWrapper implements IBank{ public void transfer(Account from, Account to, double amount) { StockClass s = new StockClass(); s.transfer(from, to, new Money(amount)); } Create an Adapter class So casting will NOT do …

58 Will the old code work? class BankClass implements IBank { public static void main(String[] args) { } BankClass b = new BankClass(); StockClassWrapper obj = new StockClassWrapper(); obj.transfer(b.getAccount(12345), b.getAccount(45567), 400); public class StockClassWrapper implements IBank{ public void transfer(Account from, Account to, double amount) { StockClass s = new StockClass(); s.transfer(from, to, new Money(amount)); }

59 Now the client class need not change …
Will the old code work? class BankClass implements IBank { public static void main(String[] args) { } Now the client class need not change … BankClass b = new BankClass(); StockClass obj = new StockClass(); obj.transfer(b.getAccount(12345), b.getAccount(45567), 400); public class StockClass implements IBank{ public void transfer(Account from, Account to, double amount) { OldStockClass s = new OldStockClass(); s.transfer(from, to, new Money(amount)); }

60 Adapter Pattern Summary
“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

61 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

62 Bridge Pattern

63 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. 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.

64 Pattern Description Template
64

65 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 Design patterns must be described using consistent format (Gamma). Each pattern is divided into these sections according to the presented template. Pattern name and classification Intent A statement of a problem which describes intent, that is the goals and objectives it wants to reach within given contexts and force. -Motivation - A scenario that illustrates a design problem and how the class and object structures in the pattern solve the problem. Applicability - The situations in which the problem and its solution seem to recur, and for which the solution is desirable. It can be thought of as the initial configuration of a system before the pattern is applied to it. Structure - A graphical representation of the classes in the pattern using notation based on the Object Modeling technique. Participants - Collaborations - How the partic… Consequences - of applying the pattern, both good and bad, and other problems and patterns that may arise from the new context. It describes the postconditions and side-effects of the pattern. Implementation - What pitfalls, hints, or techniques should you be aware of when implementing the patterns? What are language-specific issues? Related patterns - What design patterns are closely related to this one? What are important differences? With which other patterns should this one be used?

66 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

67 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 Several different formats have been used for describing patterns The pattern description format used in Alexander's work is called the "Alexandrian form". The format used in [GoF] is referred to as "GoF format". NAME - pattern must have a meaningful name. This allows us to use a single word or short phrase to refer to the pattern Good pattern names form a vocabulary for discussing conceptual abstractions. Sometimes a pattern may have more than one commonly used name in the literature. In this case it is common practice to document these nicknames or synonyms under the heading of Aliases or Also Known As. PROBLEM - the problem pattern is trying to solve (if people know what the problem the pattern solves, they’ll know when to apply it. CONTEXT - A pattern solves a problem in a given context and it may not make sense elswhere.The preconditions under which the problem and its solution seem to recur, and for which the solution is desirable. This tells us the pattern's applicability. It can be thought of as the initial configuration of the system before the pattern is applied to it. FORCES- A concrete scenario which serves as the motivation for the pattern is frequently employed … Not all problems are clear cut. Forces make clear intricacies of a problem) SOLUTION- The solution should describe not only static structure but also dynamic behavior. The static structure tells us the form and organization of the pattern, but often it is the behavioral dynamics that make the pattern "come alive". The description of the pattern's solution may indicate guidelines to keep in mind (as well as pitfalls to avoid) when attempting a concrete implementation of the solution.

68 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 EXAMPLES - are present in all good patterns, visual analogies are good for pattern. Examples help thereader understand the pattern's use and applicability. Visual examples and analogies can often be especially illuminating. An example may be supplemented by a sample implementation to show one way the solution might be realized. FORCE RESLOUTION or RESULTING CONTEXT - Few patterns are perfect or stand on their own. A good pattern tells what forces it leaves unresolved, or what other pattern must be applied, and how the context is changed by the pattern. The state or configuration of the system after the pattern has been applied, including the consequences (both good and bad) of applying the pattern, and other problems and patterns that may arise from the new context. It describes the postconditions and side-effects of the pattern. RATIONALE - This tells where the pattern comes from, why it works, and why expert use.The rationale provides insight into the deep structures and key mechanisms that are going on beneath the surface of the system. RELATED PATTERNS - The static and dynamic relationships between this pattern and others within the same pattern language or system. KNOWN uses - Describes known occurrences of the pattern and its application within existing systems. This helps validate a pattern by verifying that it is indeed a proven solution to a recurring problem. Known uses of the pattern can often serve as instructional examples

69 Design Patterns – Summative Evaluation
69 List six benefits of design pattern usage in software engineering.

70 Summary 70

71 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.

72 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”

73 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

74 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

75 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

76 Patterns & Model-Driven Development
76 Something to ponder as you leave: How can design patterns aid MDE?

77 Online resources Pattern FAQ Basic patterns Patterns home page
Basic patterns Patterns home page

78 Other resources Design Patterns – Elements of Reusable Object-Oriented Software – Erich Gamma, et. Al, ISBN Java Design Patterns – James W. Cooper, ISBN Head First Design Patterns – Eric & Elisabeth Freeman (with Kathy Sierra & Bert Bates) – ISBN

79 The End Qu es ti ons? ______________________ Devon M. Simmonds
Computer Science Department University of North Carolina Wilmington _____________________________________________________________

80 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);

81 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; }

82 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(); }

83 Observer design pattern: example 2

84


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

Similar presentations


Ads by Google