1 / 44

Design Patterns

Design Patterns. Introduction. Course Description . Traditionally, OO designers have developed their own private "catalogs" of solutions to recurring design problems. More recently, advocates of design patterns have created public repositories of patterns that more formally

giulia
Download Presentation

Design Patterns

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Design Patterns Introduction

  2. Course Description • Traditionally, OO designers have developed their own private "catalogs" of solutions to recurring design problems. • More recently, advocates of design patterns have created public repositories of patterns that more formally • Identify these recurring design problems • Document possible solutions to these problems through the general arrangement and composition of objects and classes • Discuss the advantages and disadvantages of the various solutions and • Provide implementation examples. This course will introduce the student to the concept of design patterns, examine several patterns in detail, apply these patterns to specific problems, and point the student to design pattern resources.

  3. Recommended Textbooks • Recommended Text • Design Patterns: Elements of Reusable Object-Oriented Software (1995) by Gamma; ISBN 0-201-63361-2 published by Pearson Education • Additional Reading • Head First Design Patterns (2004) by Freeman; ISBN 0-596-00712-4 published by O'Reilly and Assoc.

  4. Marks Distribution • 6-8 Quizzes: 15% • 2 Assignments: 25% • Mid term Exam:30% • Final Exam: 30%

  5. Outline • Introduction to Design Patterns • Describing Design Patterns • The Design Patterns Catalog • How to Select and Use a Design Pattern • Creational Patterns • Abstract Factory, Builder, Singleton etc. • Structural Patterns • Adapter, Bridge, Composite etc. • Behavioral Patterns • Command, Interpreter, Observer, Strategy etc.

  6. What’s a good object oriented design • Design should be SPECIFIC to the problem at hand AND • Also be GENERIC enough to address future problems and requirements • So the design should be REUSABLE • Expert designers REUSE successful designs • Consequently REUSABLE designs are recurring PATTERNS of classes and objects in OO Systems

  7. REUSABILITY EXAMPLE • Novelists & Playwrights seldom write from scratch INSTEAD • Follow PATTERNS like ‘Tragically flawed Hero’ (Macbeth, Hamlet) or ‘The Romantic Novel’

  8. What is a design pattern • “A proven solution to a common problem in a specified context.” • Example: We can light a candle if light goes out at night • Christopher Alexander (Civil Engineer) in 1977 wrote • “A 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” • The “gang of four” (GoF) • In 1995, the principles that Alexander established were applied to software design and architecture. The result was the book: • “Design Patterns: Elements of Reusable Object-Oriented Software” by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides.

  9. Why learn Design Patterns • They make it easier to reuse successful designs and architectures • They can make documentation and maintenance of the systems easier • Design Patterns help a designer design “right” faster • They provide a vocabulary that can be used amongst software developers. • Enable us to discuss low-level implementation in a high-level, abstract manner. • Help in extendibility and avoiding solution redesign

  10. Elements of a Design Pattern • Pattern Name • Is a handle to describe design problem & solution • Problem • Describes when a Pattern is to be applied • Solution • General arrangement of elements to solve a problem • Consequences • Results and Tradeoffs of applying a Pattern • Tradeoffs can be space, time, language etc.

  11. Describing a Design Pattern • Pattern Name & Classification – Conveys the essence of the pattern concisely • Intent – What design issue the pattern addresses • Also Known As – Other well known names for this pattern • Motivation – A scenario illustrating a design problem and how its being solved by the pattern • Applicability – Known situations where the pattern can be applied • Structure – OMT (Object Modeling ) based graphic representation of the classes in the pattern • Participants – Classes and objects in the pattern with their responsibilities

  12. Describing a Design Pattern Cont’d • Collaborations – How the participants collaborate to carry out their responsibilities • Consequences – What are the results and tradeoffs of using the pattern • Implementation – Hints on implementation of the pattern like language dependency • Sample Code – Sample code • Known Uses – Examples • Related Patterns – Other patterns closely related with the pattern under consideration

  13. Not a Design Pattern • Linked Lists • Hash Tables • Domain Specific designs for entire application or subsystem • A code solution ready for copy-and-paste • Programming language features • The same every time you see them

  14. MVC Pattern • The main purpose of using MVC pattern is to decouple the GUI from the Data. It also • gives the ability to provide multiple views for the same Data. • MVC pattern separates views and models by establishing a subscribe/notify protocol amongst them • Application of MVC pattern has benefits like • Classes defining application data and presentation can be reused. • 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

  15. Relative Percentages A B C D A X 15 35 35 15 D B Y 10 40 30 20 C Z 10 40 30 20 A B C D A=10% B=40% C=30% D=20% Application data Change notification Requests, modifications MVC Pattern Cont’d Model

  16. MVC Pattern Cont’d • Model: - This section is specially for maintaining data. It is actually where your business logic, querying database, database connection etc. is actually implemented. • Views: - Displaying all or some portion of data, or probably different view of data. View is responsible for look and feel, Sorting, formatting etc. • Controller: - They are event handling section which affects either the model or the view. Controller responds to the mouse or keyboard input to command Model and View to change. Controllers are associated with views. User interaction triggers the events to change the Model, which in turn calls some methods of Model to update its state to notify other registered Views to refresh their display.

  17. Design Patterns Classification • According to the GOF, the design patterns can be classified in two ways • According to the PURPOSE • According to the SCOPE • PURPOSE of Design Patterns reflect what actually they do • SCOPE of Design Patterns reflect whether they apply primarily to Classes or Objects.

  18. Purpose based Design Patterns Classification • Creational – Concerned with the purpose of object creation or class instantiation • Structural – Deal with composition of classes and objects • Behavioral – Characterize the ways in which classes and objects interact and distribute resposibility.

  19. Scope Based Design Patterns Classification • Class Patterns deals with the relationships amongst the classes and their subclasses • These relationships are established through INHERITANCE, so they are static – fixed at compile time • Object Patterns deals with object relationships which can be changed at runtime or are dynamic • Note that most patterns are object patterns

  20. Purpose & Scope based Design Patterns Classification • Creational Class patterns defer some part of object creation to subclasses where as creational object patterns defer it to another object. • Structural class patterns use inheritance to compose classes, while structural object patterns describe ways to assemble objects. • Behavioral class patterns use inheritance to describe algorithms and flow of control, whereas the behavioral object patterns describe how a group of objects cooperate to perform a task

  21. Design Patterns Classification

  22. How Design Patterns Solve Design Problems • Finding appropriate objects • The hard part about OOD is decomposing a system into objects • They help to introduce an abstraction for treating objects uniformly that doesn’t have a physical counterpart • They help to identify less obvious abstractions and objects that can capture them • These objects are seldom identified in a design earlier and are discovered while making the design reusable and more flexible • Determining the object Granularity • They help in specifying how to represent complete subsystems as objects • They help you in decomposing objects into smaller objects

  23. How Design Patterns Solve Design Problems • Specifying Object Interfaces • Help you in defining interfaces and the kinds of data that get sent across them • Might also tell what NOT to put into an interface • Also specify relationships across interfaces • Designing for Change • Help you to avoid dependence on specific operations • Help you to avoid dependence on hardware and software platforms • Help to avoid algorithmic dependencies

  24. Patterns and Algorithms • Algorithms and data structures generally solve more fine-grained computational problems like sorting and searching. • Patterns are typically concerned with broader architectural issues that have larger-scale effects.

  25. Patterns and Frameworks • A software framework is a set of cooperating classes that make up a reusable design for a specific class of software [Deu89,JF88] • A framework will dictate overall structure, partitioning of classes and objects, how the classes or objects collaborate • A framework is usually not a complete application: it often lacks the necessary application-specific functionality. • Examples • Framework for building compiler for different languages and machines. • For building financial modeling applications

  26. Patterns and Frameworks • Design patterns may be employed both in the design and the documentation of a framework. A single framework typically encompasses several design patterns. A framework can be viewed as the implementation of a system of design patterns. • Frameworks and design patterns are distinct: a framework is executable software, design patterns represent knowledge and experience about software. Frameworks are of a physical nature, patterns are of a logical nature: frameworks are the physical realization of one or more software pattern solutions; patterns are the instructions for how to implement those solutions. • Major differences: • Design patterns are more abstract than frameworks. • Design patterns are smaller architectural elements than frameworks. • Design patterns are less specialized than frameworks.

  27. An Example Case • Goals • Learn how to exploit and gain experience of others • Examine the benefits of design pattern • Learn one specific pattern: Strategy pattern

  28. Duck quack() swim() display() // other duck methods Simple Simulation of Duck behavior RedheadDuck MallardDuck Other duck types display() // looks like redhead display() // looks like mallard

  29. Simple Simulation of Duck behavior • All ducks Quack and Swim the super class DUCK takes care of the implementation code. But • Each duck subtype is responsible for implementing its own Display method as each duck looks different • In the super class the Display method is abstract.

  30. Duck quack() swim() display() fly() // other duck methods What if we want to simulate flying ducks? RedheadDuck MallardDuck Other duck types display() // looks like redhead display() // looks like mallard

  31. Duck quack() swim() display() fly() // other duck methods RubberDuck RedheadDuck MallardDuck quack() //overridden to squeak display() // looks like rubberduck fly() // override to do nothing display() // looks like redhead display() // looks like mallard Tradeoffs in use of inheritance and maintenance One could override the fly method to the appropriate thing – just as the quack method below.

  32. DecoyDuck quack(){ // override to do nothing } display() // display decoy duck fly (){ //override to do nothing } Example complicated: add a wooden decoy ducks to the mix Inheritance is not always the right answer. Every new class that inherits unwanted behavior needs to be overridden. How about using interfaces instead?

  33. Using Interfaces in Our Example • We can take Fly() out of the superclasses • We make an interface iFlyable containing the Fly() method. That way the ducks supposed to fly can implement that interface and have a Fly() method • Same solution can be implemented for Quack(), we can make interface iQuackable containing the Quack() method

  34. Quackable Flyable Duck quack() fly() swim() display() // other duck methods RubberDuck DecoyDuck display() quack() display() MallardDuck RedheadDuck display() fly() quack() display() fly() quack() Duck simulation recast using interfaces Interfaces

  35. Pros & Cons • Not all inherited methods make sense for all subclasses – hence inheritance is not the right answer • But by defining interfaces, every class that needs to support that interface needs to implement that functionality… destroys code reuse and creates a maintenance issue. • So if you want to change the behavior defined by interfaces, every class that implements that behavior may potentially be impacted AND • Change is constant in Software Development • Overtime an application must change and grow or it will die…

  36. Design Principles to the Rescue • Identify the aspects of your application that vary and separate them from what stays the same. OR Take the parts that vary and encapsulate them, so that later you can alter or extend the parts that vary without affecting those that don’t. • Program to an interface, not to an implementation (Discussed Later)

  37. Change in Duck Classes According to the Design Principle • As far as we can tell other than the problems with Fly() and Quack() the Duck Class is fine. • Now to separate “the parts that change from those which remain the same”, we can create two sets of classes apart from the Duck Class. • One set can represent the Quacking behaviors e.g. a class implements quacking, another implements squeaking etc. • Similar is the case with Flying behaviors

  38. Design Principle • Program to an interface, not to an implementation • We will use interfaces to represent each behavior • Each Implementation of behavior will implement these interfaces • So the duck classes won’t implement these interfaces instead the set of classes for behavior would implement them. • With our new design the duck classes would USE a behavior represented by an interface. OR • The actual implementation won’t be locked in the duck classes.

  39. <<interface>> FlyBehavior <<interface>> QuackBehavior fly() quack() FlyWithWings Quack FlyNoWay Squeak MuteQuack fly(){ // implements duck flying } quack(){ // implements duck quacking } fly(){ // do nothing – Can’t fly } quack(){ // implements duck squeak } quack(){ // do nothing – Can’t quack } Implementing duck behaviors - revisited Key now is that Duck class will delegate its flying and quacking behavior instead of implementing these itself

  40. Duck FlyBehavior: flyBehavior QuackBehavior: quackBehavior performQuack() swim() display() performFly() //other duck-like methods In the Duck simulation context… Duck Behaviors Flying Behaviors Quacking Behaviors 41

  41. <<interface>> FlyBehavior Duck fly() FlyBehavior: flyBehavior QuackBehavior: quackBehavior performQuack() performFly() setFlyBehavior() setQuackBehavior() swim() display() FlyWithWings FlyNoWay fly() // implements duck flying fly() // do nothing – Can’t fly <<interface>> QuackBehavior quack() DecoyDuck MallardDuck RubberDuck Quack Squeak quack() // implements squeak quack() // implements duck quacking RedHeadDuck display() display() display() display() Mutequack quack() // do nothing Duck simulation recast using the new approach

  42. Design Principle • Favor composition over inheritance • HAS-A can be better than IS-A • Composition lets you encapsulate a family of algorithms into their own set of classes. • Allows changing behavior at run time

  43. The strategy pattern The Strategy Pattern defines a family of algorithms, Encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

More Related