Software Engineering Design Patterns -- Introduction

Click here to load reader

download Software Engineering Design  Patterns --  Introduction

of 51

description

Software Engineering Design Patterns -- Introduction. Based on slides of: Mira Balaban Department of Computer Science Ben-Gurion university F . Tip, J. Vlissides , J. Cooper, IBM T J Watson Research Center. R . Whitney, San-Diego State University. - PowerPoint PPT Presentation

Transcript of Software Engineering Design Patterns -- Introduction

Software Processes

Based on slides of: Mira Balaban Department of Computer Science Ben-Gurion university F. Tip, J. Vlissides, J. Cooper, IBM T J Watson Research Center. R. Whitney, San-Diego State University. D.C. Schmidt, Vanderbilt University.Software EngineeringDesign Patterns -- IntroductionSoftware Engineering 2011Department of Computer Science Ben-Gurion university

SourcesClassical text: Design Patterns: Elements of Reusable Object-Oriented Software, Gamma, Helm, Johnson, Vlissides, (GoF), 1995 Java Design Patterns A Tutorial, J.W. Cooper, 2000. (available online)Applied Java Patterns, S. Stelting, O. Maassen, 2002.Patterns home page: http://hillside.net/patterns/

Software Engineering, 2011Design Patterns -Introduction #What is a Pattern?The term design pattern was coined in the mid-1970s by Christopher Alexander, an architect, who abstracted common design patterns in architecture and formalized a way of describing the patterns in a pattern language. A design pattern addresses both a problem that occurs repeatedly in our environment and the core of the solution to that problembut at a level of generality that the solution can be applied many times without ever being the same in its particulars.

Software Engineering, 2011Design Patterns -Introduction #What is a Pattern? "Each pattern is a three-part rule, which expresses a relation between a certain context, a problem, and a solution"Christopher Alexander on architecture patternsA Pattern Language, Christopher Alexander, 1977

"Patterns are not a complete design method; they capture important practices of existing methods and practices uncodified by conventional methods"James CoplienSoftware Patterns, James Coplien, 1996, 2000,http://www1.belllabs.com/user/cope/Patterns/WhitePaper/

Software Engineering, 2011Design Patterns -Introduction #Example: A Place To Wait (Alexander 1977)Fundamental problem: How to spend time wholeheartedly and Still be on hand when doctor, airplane etc arriveThe solution:Fuse the waiting with other activity that keeps them in earshotPlayground beside Pediatrics ClinicHorseshoe pit next to terrace where people waitedAllow the person to become still meditativeA window seat that looks down on a streetA protected seat in a gardenA dark place and a glass of beerA private seat by a fish tank

Software Engineering, 2011Design Patterns -Introduction #Example: A Place To Wait (Alexander 1977)The Solution:"In places where people end up waiting create a situation which makes the waiting positive. Fuse the waiting with some other activity - newspaper, coffee, pool tables, horseshoes; something which draws people in who are not simple waiting. And also the opposite: make a place which can draw a person waiting into a reverie; quiet; a positive silence

The active part might have a window on the street - STREET WINDOWS (164), WINDOW PLACE (180), a cafe - STREET CAFE (88), games, positive engagements with the people passing by - OPENING TO THE STREET (165). The quiet part might have a quiet garden seat - GARDEN SEAT (176), a place for people to doze SLEEPING IN PUBLIC (94), perhaps a pond with fish in it - STILL WATER (71). To the extent that this waiting space is a room, or a group of rooms, it gets its detailed shape from LIGHT ON TWO SIDES OF EVERY ROOM (159) and THE SHAPE OF INDOOR SPACE (191). Software Engineering, 2011Design Patterns -Introduction #Example: Chicken and Egg (Anthony 1996)The ProblemTwo concepts are each a prerequisite of the otherTo understand A one must understand BTo understand B one must understand AA "chicken and egg" situation

Patterns for Classroom Education, Dana Anthony, pp. 391-406, Pattern Languages of Program Design 2, Addison Wesley, 1996

Software Engineering, 2011Design Patterns -Introduction #Example: Chicken and Egg (Anthony 1996)Constraints and ForcesFirst explain A then BEveryone would be confused by the endSimplify each concept to the point of incorrectness to explain the other onePeople don't like being lied toThe SolutionExplain A & B correctly by superficiallyIterate your explanations with more detail each iterationSoftware Engineering, 2011Design Patterns -Introduction #Example: A Pattern Language for the Preparation of Software Demonstrations (Coram 1996)The patterns:Element IdentificationCatalytic ScenariosMutable CodePrototyping LanguagesLightweight User InterfacesJudicious FireworksArchive Scenarios

Demo Prep: A Pattern Language for the Preparation of Software Demonstrations, Todd Coram, pp. 407-416, Pattern Languages of Program Design 2, Addison Wesley, 1996

Software Engineering, 2011Design Patterns -Introduction #Pattern 1: Element Identification (Coram 1996)The Problem:Selecting the right features to demo is a critical part of keeping the customer's confidenceThe ContextHave requirementsWorking on demo to easy customers doubts about committing to or continuing with the software projectForcesNeed to demonstrate your ability to deliver "things that work"Need to show some level of functionalityCustomer wants to see the product's face - the GUIIf customer is not happy with the demo, they are not likely to like the end productDemos build confidence and create anticipationSoftware Engineering, 2011Design Patterns -Introduction #Pattern 1: Element Identification (Coram 1996)The Solution:Identify key areas that concern the customerTalk to the customerListen carefullyStay away from excessive animations or other visualembellishmentsUnless the product is a game, the product is to help thecustomer get some work done not to entertain peopleThe product's face can be shown through Lightweight UserInterface (pattern 5)Functionality can be addressed by Prototyping Languages(pattern 4)Software Engineering, 2011Design Patterns -Introduction #Pattern 2: Catalytic Scenarios (Coram 1996)The Problem:The customer has specified what they think they wantYou don't want to build the wrong thingThe ContextStarting a project to develop software based on requirements and specification that have already been agreed onThe ForcesCustomer may not really know what they wantRequirements may not accurately reflect customer's requirementsRequirements may be ambiguousCustomer expects to be given vision of the finished productDemos consume developer's resourcesSoftware Engineering, 2011Design Patterns -Introduction #Pattern 2: Catalytic Scenarios (Coram 1996)The Solution:Use demonstrable scenarios as a catalyst to open a dialoguebetween you and the customerIf the specs are ambiguous - develop alternative scenariosDo not demonstrate capabilities that will be hard toincorporate into your designIf you do not want to change the spec make sure the demoscenarios follow the specKeep demo scenarios simple and shortSoftware Engineering, 2011Design Patterns -Introduction #Pattern 3: Mutable Code (Coram 1996)The Problem:How much code should you write for the demo?The ContextYou have identified your Catalytic Scenarios and are evaluating the amount of effort required to develop themThe ForcesSome demo codeCan not be used in the end productShould not be used in the end productDevelopment time for demo impacts product developmentCustomer does not like to pay for developing something twiceSoftware Engineering, 2011Design Patterns -Introduction #Pattern 3: Mutable Code (Coram 1996)The Solution:Build modifiable codeUse tools that support a high level of abstractionGUI buildersScripting languagesWrite as little code as possible for the demoUse as much real code as you canIf you build screens then use Lightweight User InterfacesPrototyping Languages (pattern 4) discusses integrating demo code into end productSoftware Engineering, 2011Design Patterns -Introduction #Patterns of Learning (D.C. Schmidt)Successful solutions to many areas of human endeavor are deeply rooted in patterns An important goal of education is transmitting patterns of learning from generation to generation

Learning to develop good software is similar to learning to play good chess

Software Engineering, 2011Design Patterns -Introduction #Becoming a Chess Master (D.C. Schmidt)First learn the rules e.g., names of pieces, legal movements, chess board geometry and orientation, etc.

Then learn the Principles e.g., relative value of certain pieces, strategic value of center squares, power of a threat, etc.

To become a master of chess, one must study the games of other masters These games contain patterns that must be understood, memorized, and applied repeatedly

There are hundreds of these patterns

Software Engineering, 2011Design Patterns -Introduction #What are design patterns? (J.W. Cooper)Recurring solutions to design problems you see over and over. (Alpert et al, 1998)

A set of rules describing how to accomplish certain tasks in the realm of software development. (Pree, 1994)

Focus on reuse of recurring architectural design themes (Coplien and Schmidt, 1995)

Address a recurring design problem that arises in a specific context and presents a solution to it (Buschmann. et al, 1996)

Identify and specify abstractions that are above the level of single classes or instances, or of components. (GoF)Software Engineering, 2011Design Patterns -Introduction #More Paradigms of design patternsProblem Analysis (Fowler)

Enterprise systems (Fowler)

Responsibility assignment in system design (Larman)

User interfaces.

Web site construction.

Software design (GoF, Coplien, and others)Software Engineering, 2011Design Patterns -Introduction #What is a Software design pattern? (F. Tip)Related question: what is the difference between experienced and inexperienced software designers?experienced designers :know from experience what works and what doesntable to recognize standard design problems and apply proven solutions to them

Definition of a software design pattern:a description of communicating classes and objects that are customized to solve a general design problem in a particular contextSoftware Engineering, 2011Design Patterns -Introduction #Stages of Design Pattern awareness(J. Vlissides)IgnoranceconsternationinitiationunderstandingfamiliaritybenefitSoftware Engineering, 2011Design Patterns -Introduction #Consternation fear worry confusionLearn to apply design patterns to the design process (J. Vlissides)find the right patternsunderstand (un)applicabilitysee when and how to bend a patternevaluate design trade-offs effectively

Learn by (counter) exampleSoftware Engineering, 2011Design Patterns -Introduction #Software Design Patterns - Motivation OOD methods emphasize design notationsFine for specification, documentationBut OOD is more than just drawing diagramsGood draftsmen good designersGood OO designers rely on lots of experienceAt least as important as syntaxMost powerful reuse is design reuseMatch problem to design experience

Software Engineering, 2011Design Patterns -Introduction #

Recurring Design StructuresOO systems exhibit recurring structures that promote abstractionFlexibilityModularityelegance

Therein lies valuable design knowledgeProblem: capturing, communicating, & applying this knowledge

Software Engineering, 2011Design Patterns -Introduction #Design PatternsA design Patternabstracts a recurring design structurecomprises class and/or objectdependenciesstructuresinteractionsConventionsnames & specifies the design structure explicitly purify design experience

Software Engineering, 2011Design Patterns -Introduction #Elements of Design Patterns (F. Tip) A design pattern has 4 elements:a name (e.g, Abstract Factory or Visitor)the problem that the pattern addressesthe solution: the program constructs that are part of the patternthe consequences: the results and tradeoffs of applying the patternother factors:problem & solution have been observed in practicechoice of implementation language importantSoftware Engineering, 2011Design Patterns -Introduction #GoalsCodify good designdistill & generalize experienceaid to novices & experts alikeGive design structures explicit namescommon vocabularyreduced complexitygreater expressivenessCapture & preserve design informationarticulate design decisions succinctlyimprove documentationFacilitate restructuring/refactoringpatterns are interrelatedadditional flexibility

Software Engineering, 2011Design Patterns -Introduction #Classifying Design Patterns (F. Tip) purpose: what a pattern doescreational: concerned with creation of objectsstructural: related to composition of classes or objects behavioral: related to interaction and distribution of responsibilityscopeclass-level: concerned with relationship between classes and their subclassesobject-level: concerned with object relationship (more dynamic, may be changed at run-time)Software Engineering, 2011Design Patterns -Introduction #GoF Design Patterns Classified (F. Tip)

Software Engineering, 2011Design Patterns -Introduction #See p.10Principles of Object-Oriented Design (F. Tip) Program to an interface, not an implementation.

Favor object composition over class inheritance.Software Engineering, 2011Design Patterns -Introduction #p.20Class vs. Interface Inheritance (F. Tip) Class inheritance defines an objects implementation in terms of another objects implementationmechanism for code & representation sharingInterface inheritance describes when an object can be used in place of another (subtyping)many languages (e.g., C++) dont make this distinction, but Java doesAn object's class defines how the object is implemented. The class defines the object's internal state and the implementation of its operations.

An object's type only refers to its interfacethe set of requests to which it can respond. An object can have many types, and objects of different classes can have the same typeSoftware Engineering, 2011Design Patterns -Introduction #See p. 17Class vs. Interface Inheritance (2) (F. Tip) benefits of class inheritanceextend an applications functionality by reusing functionality in parent classeslets you get new implementations almost for free, inheriting most of what you need from existing classesbenefits of interface inheritanceclients remain unaware of specific types of objects they use, and of the classes that implement these objectsusing interface inheritance greatly reduces dependencies between subsystemsreduces the impact of changesSoftware Engineering, 2011Design Patterns -Introduction #In C++ interface defined by abstract classesMechanisms for Reusing Functionality (F. Tip) Inheritance versus Compositionclass inheritance: define implementation of one class in terms of anotheroften referred to as white-box reuse: internals of parent class visible to extending classclass inheritance breaks encapsulation

object composition: compose objects to get new, more complex functionalityimplemented by giving objects references to other objects; access these objects via interfacesrequires that objects have well-defined interfacesoften called black-box reuse: no internal details of objects are visible to the class that uses themcomposition does not break encapsulationSoftware Engineering, 2011Design Patterns -Introduction #p.19 Pros & Cons of Class Inheritance (F. Tip) Advantages:directly supported by the programming language, hence easy to usemakes it easy to modify the reused implementation (by simply overriding a few methods)

Disadvantages:cannot change inherited functionality at run-time, because inheritance is fixed at compile-timeparent classes define at least part of their subclasses physical representation, and subclasses are exposed to details of their parents implementationimplementation of subclass becomes very tightly coupled with implementation of parentchange in parent is likely to require changes in subclassSoftware Engineering, 2011Design Patterns -Introduction #Delegation (F. Tip) delegation is an alternative to inheritance:two objects are involved: a receiving object delegates an operation to its delegateanalogy: a subclass that defers a request to its parent classsuppose an object of type C wants to delegate a method f() to an object of type D: class D defines method f()class C needs to contain a reference field d to a D-object, which needs to be initializedC needs a forwarding method f() that calls f() on d Software Engineering, 2011Design Patterns -Introduction #Delegation: Example (F. Tip) public class Rectangle { private int width; private int height; public int area(){ return width * height; } }

public class Window { private Rectangle rect; public int area(){ return rect.area(); }}

public class WindowClient { void someOperation(Window w){ ... w.area() ... }}class Window delegates its area() operation to a Rectangle instanceSoftware Engineering, 2011Design Patterns -Introduction #(Ab)use inheritance for the same purpose (F. Tip) public class Rectangle { private int width; private int height; public int area(){ return width * height; } }

public class Window extends Rectangle { private Rectangle rect; // method area() inherited from superclass }

public class WindowClient { void someOperation(Window w){ ... w.area() ... }}Software Engineering, 2011Design Patterns -Introduction #Why use delegation? (F. Tip) inheritance can be more convenient:only define method f() onceno need to forward callssomewhat more efficient

however, it is less flexible:cannot change the implementation of f() after creating the objectin languages with single inheritance, you can only inherit methods from one superclassSoftware Engineering, 2011Design Patterns -Introduction #True delegation (F. Tip) with inheritance, the method in the superclass can use dynamic dispatch to invoke methods in a subclasswith delegation, this requires some extra work:pass receiving objects this pointer as an argument to the delegatedelegate invokes methods on this reference when it needs to invoke methods on receiving objectthis form of delegation is called true delegation for an example of true delegation, see the State design patternSoftware Engineering, 2011Design Patterns -Introduction #When to use inheritance? (F. Tip) generally speaking, use inheritance for:is-a relationships that dont change over timesituations where the class containing the actual operation is abstractgenerally speaking, use delegation for:has-a, part-of relationshipsis-a-role-played-by relationshipsrelationships that change over timesituations where multiple inheritance would be needed (if language doesnt allow MI)Software Engineering, 2011Design Patterns -Introduction #Designing for change (F. Tip) many design patterns introduce flexibility to avoid common causes of redesign such as:creating an object by specifying a class explicitlydependence on specific operationsdependence on hardware/software platformdependence on object representations or implementationsalgorithmic dependenciestight couplingextending functionality by subclassinginability to alter classes conveniently Software Engineering, 2011Design Patterns -Introduction #Designing for change (R. Whitney) Some common design problems that GoF patterns thatAddress:Creating an object by specifying a class explicitlyAbstract factory, Factory Method, PrototypeDependence on specific operationsChain of Responsibility, CommandDependence on hardware and software platformsAbstract factory, BridgeDependence on object representations or implementationsAbstract factory, Bridge, Memento, ProxySoftware Engineering, 2011Design Patterns -Introduction #Designing for change (R. Whitney) Algorithmic dependenciesBuilder, Iterator, Strategy, Template Method, VisitorTight CouplingAbstract factory, Bridge, Chain of Responsibility, Command, Facade, Mediator, ObserverExtending functionality by subclassingBridge, Chain of Responsibility, Composite, Decorator,Observer, StrategyInability to alter classes convenientlyAdapter, Decorator, VisitorSoftware Engineering, 2011Design Patterns -Introduction #GOF: Describing Design PatternsPattern Name and Classification The pattern's name conveys the essence of the pattern succinctly. A good name is vital, because it will become part of your design vocabulary. Intent A short statement that answers the following questions: What does the design pattern do? What is its rationale and intent? What particular design issue or problem does it address? Also Known As Other well-known names for the pattern, if any. Motivation A scenario that illustrates a design problem and how the class and object structures in the pattern solve the problem. The scenario will help you understand the more abstract description of the pattern that follows. Applicability What are the situations in which the design pattern can be applied? What are examples of poor designs that the pattern can address? How can you recognize these situations? Structure A graphical representation of the classes in the pattern using a notation based on the Object Modeling Technique , interaction diagrams to illustrate sequences of requests and collaborations between objects. GOF: Describing Design PatternsParticipants The classes and/or objects participating in the design pattern and their responsibilities. Collaborations How the participants collaborate to carry out their responsibilities. Consequences How does the pattern support its objectives? What are the trade-offs and results of using the pattern? What aspect of system structure does it let you vary independently? Implementation What pitfalls, hints, or techniques should you be aware of when implementing the pattern? Are there language-specific issues? Sample Code Code fragments that illustrate how you might implement the pattern in C++ or Smalltalk. Known Uses Examples of the pattern found in real systems. We include at least two examples from different domains. Related Patterns What design patterns are closely related to this one? What are the important differences? With which other patterns should this one be used?

Example: The Model/View/Controller (MVC)MVC consists of three kinds of objects. The Model is the application object the View is its screen presentation the Controller defines the way the user interface reacts to user input. Before MVC, user interface designs tended to lump these objects together. MVC decouples them to increase flexibility and reuse.MVC decouples views and models by establishing a subscribe/notify protocol between them.A view must ensure that its appearance reflects the state of the model. Whenever the model's data changes, it notifies views that depend on it.In response, each view gets an opportunity to update itself. This approach lets you attach multiple views to a model to provide different presentations. You can also create new views for a model without rewriting it.

Software Engineering, 2011Design Patterns -Introduction #A common pattern cited in early literature on programming frameworks is Model-View-Controller (MVC) for Smalltalk [Krasner and Pope, 1988], which divides the userinterface problem into three parts

Example: The Model/View/Controller (MVC)Example: a model and three views. (controllers are not shown) The model contains some data values, and the views defining a spreadsheet, histogram, and pie chart display these data in various ways. The model communicates with its views when its values change, and the views communicate with the model to access these values.

Software Engineering, 2011Design Patterns -Introduction #Example: The Model/View/Controller (MVC)This example reflects a design that decouples views from models.The design is applicable to a more general problem: decoupling objects so that changes to one can affect any number of others without requiring the changed object to know details of the others. This more general design is described by the Observer design pattern.Another feature of MVC is that views can be nested. For example, a control panel of buttons might be implemented as a complex view containing nested button views. The user interface for an object inspector can consist of nested views that may be reused in a debugger.Software Engineering, 2011Design Patterns -Introduction #Example: The Model/View/Controller (MVC) MVC supports nested views with the CompositeView class, a subclass of View. CompositeView objects act just like View objects; a composite view can be used wherever a view can be used, but it also contains and manages nested views.This design is applicable to a more general problem, which occurs whenever we want to group objects and treat the group like an individual object. This more general design is described by the Composite design pattern. It lets you create a class hierarchy in which some subclasses define primitive objects (e.g., Button) and other classes define composite objects that assemble the primitives into more complex objects.

Software Engineering, 2011Design Patterns -Introduction #Example: The Model/View/Controller (MVC)MVC lets you change the way a view responds to user input without changing its visual presentation. You might want to change the way it responds to the keyboard, for example, or have it use a pop-up menu instead of command keys. MVC encapsulates the response mechanism in a Controller object. There is a class hierarchy of controllers, making it easy to create a new controller as a variation on an existing one.A view uses an instance of a Controller subclass to implement a particular response strategy; to implement a different strategy, simply replace the instance with a different kind of controller. It's even possible to change a view's controller at run-time to let the view change the way it responds to user input. For example, a view can be disabled so that it doesn't accept input simply by giving it a controller that ignores input events.Software Engineering, 2011Design Patterns -Introduction #Example: The Model/View/Controller (MVC)The View-Controller relationship is an example of the Strategy design pattern. A Strategy is an object that represents an algorithm. It's useful when you want to replace the algorithm either statically or dynamically, when you have a lot of variants of the algorithm, or when the algorithm has complex data structures that you want to encapsulate.MVC uses other design patterns, such as Factory Method to specify the default controller class for a view and Decorator add scrolling to a view. But the main relationships in MVC are given by the Observer, Composite, and Strategy design patterns.

Software Engineering, 2011Design Patterns -Introduction #