Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSCE 431: (Object Oriented) Design Patterns Some material from R. Martin, Bruegge, Dutoit.

Similar presentations


Presentation on theme: "CSCE 431: (Object Oriented) Design Patterns Some material from R. Martin, Bruegge, Dutoit."— Presentation transcript:

1 CSCE 431: (Object Oriented) Design Patterns Some material from R. Martin, Bruegge, Dutoit

2 Outline Context Some key concepts and notions of OO Design patterns A few more design patterns Idioms Summary CSCE 431 OO Design Patterns

3 Context 1.Requirements elicitation  Functional model (use cases, formal specifications etc.)  Non-functional requirements 2.Analysis  Analysis Object Model (class diagrams)  Dynamic Model (state charts, sequence diagrams) 3.System design  Design goals  Subsystem decomposition 4.Object design  Object design model (class diagrams) 5.Implementation  Source code 6.Testing  Deliverable system CSCE 431 OO Design Patterns (we have not discussed yet)

4 System Design (One Slide Version) Subsystem decomposition Abstraction of the machine(s) Choosing middleware, GUI frameworks, class libraries, database engines Application domain components Possibly choosing off-the-shelf application domain components for select domain functionality Object design to fill in the rest Adapt reusable components Identify new solution classes Specify subsystem interfaces precisely CSCE 431 OO Design Patterns

5 Object Design Purpose Prepare for implementing the system model Transform the system model for better implementability/extensibility/performance/... Explore ways to implement the system model The result of object design should match the structure of the implementation CSCE 431 OO Design Patterns

6 Activities Reuse: identify and adapt existing solutions Off-the-shelf components Libraries Design patterns Interface specification Specs of each class interface APIs of subsystems Object model restructuring To improve some characteristics (extensibility, understandability, etc.) Object model optimization Greater speed, lower memory use, etc. CSCE 431 OO Design Patterns

7 Outline Context Some key concepts and notions of OO Design patterns A few more design patterns Idioms Summary CSCE 431 OO Design Patterns

8 Outline Some principles of object-oriented programming About modularity OO twists on modularity, inheritance Substitutability Delegation Introduction to design patterns A few design patterns CSCE 431 OO Design Patterns

9 Modularity Parnas, On the Criteria to be Used in Decomposing Systems into Modules, 1972 Every module should be known to the outside world through an official, “public” interface The rest of the module’s properties comprises its “secrets” It should be impossible to access the secrets from the outside Inheritance, encapsulation, related features in OO languages aimed at supporting information hiding Aside: Parnas says the following about OO languages Could be helpful, but not really needed Language is not the issue, design is what matters Some features make it easy to do things wrong CSCE 431 OO Design Patterns

10 Characteristics of Good Modularization Low coupling and high cohesion Minimize dependencies Changes are localized Maximize unity Modules work well together CSCE 431 OO Design Patterns

11 Encapsulation Booch The process of compartmentalizing the elements of an abstraction that constitute its structure and behavior; encapsulation serves to separate the contractual interface of an abstraction and its implementation Casual definition: bundling data and methods, with access protection Encapsulation enables object invariants to be enforced CSCE 431 OO Design Patterns

12 Inheritance Where used: 1.Organization (during analysis) Inheritance helps in expressing generalization and specialization in taxonomies that deal with the application domain Primary use: discussion with domain experts and customers 2.Reuse (during object design) Inheritance helps in reusing models and code to deal with the solution domain Goal is to reduce redundancy and obtain extensibility Primary use: developers CSCE 431 OO Design Patterns

13 Implementation vs. Interface Inheritance Implementation inheritance Also called class inheritance Goal is to extend an applications’ functionality by reusing functionality from the superclass Inherit from an existing class with some or all operations already implemented Specification inheritance Also called subtyping Inherit a specification for which to provide an implementation The specification is an abstract class with all the operations specified but not yet implemented Meyer gives a taxonomy of 13 different kinds of uses of inheritance CSCE 431 OO Design Patterns

14 Extensibility: Open Closed Principle (OCP) A module should be open for extension but closed for modification -B. Meyer (OOSC98) Essentially suggests that defining new subclasses should suffice to evolve code (maybe in Eiffel, as its type system gives considerable freedom) Nice if works Requires guessing/knowing the variation points Requires obeying Liskov Substitution Principle CSCE 431 OO Design Patterns

15 Liskov Substitution Principle Simple formulation Subclasses should be substitutable for their base classes Somewhat more precise formulation Note that notion of subtyping is behavioral Cannot be checked Let q(x) be a property provable about objects x of type T. Then q(y) should be provable for objects y of type S where S is a subtype of T -Liskov, Wing, 1994 Same in code class Base {... }; class Derived : public Base {... }; void q(Base& b); // should work, even if b an // instance of Derived CSCE 431 OO Design Patterns

16 LSP Violation “Circle is-an ellipse” class circle : public ellipse {... void set_foci ( Point p1, Point p2) { a = p1; b = p1 } } void f( Ellipse & e) { Point a( -1,0), b (1,0); e.set_foci (a, b); assert (e.get_focus_a () == a); assert (e.get_focus_b () == b); } set_foci ’s postcondition (something like a == p1, b == p2 ) not true for circles Fixes at the client calling f easily lead to Open Closed Principle violations CSCE 431 OO Design Patterns

17 LSP and Design by Contract class A p1; virtual void foo q1 } class B : public A p2; void foo q2 } What are the relations? p1?p2 q1?q2 i1?i2 A method in a derived class must Have preconditions that are no stronger than those of the base’s method it is overriding Have postconditions no weaker than those of the base’s method it is overriding “derived methods should expect no more and provide no less” CSCE 431 OO Design Patterns p1  p2 q1  q2 i1  i2

18 Inheritance vs. Delegation class HashTable { void put ( Object key, Object element ); Object get ( Object key ); boolean containsKey ( Object ); boolean containsValue ( Object );... } class MySet extends HashTable { void put ( Object element ) { if (! containsKey ( element )) { put ( element, this ); } boolean containsValue ( Object element ) { return containsKey ( element ); }... } class MySet { private Hashtable table ; MySet () { table = Hashtable (); } void put ( Object element ) { if (! containsValue ( element )) { table.put ( element, this ); } boolean containsValue ( Object element ) { return table.containsKey ( element ); }... } CSCE 431 OO Design Patterns Consider this inheritance relation: Implementation inheritance vs. delegation

19 Inheritance vs. Delegation Inheritance should be used only if real taxonomies exist If LSP (roughly) holds Delegation should be preferred when reusing implementations Next: design patterns And we will notice that most design patterns are some compositions/combinations of delegation and inheritance CSCE 431 OO Design Patterns

20 Outline Context Some key concepts and notions of OO Design patterns A few more design patterns Idioms Summary CSCE 431 OO Design Patterns

21 Design Patterns Motivation Not every problem solved with a solution developed “from scratch” Desirable to reuse solutions Recording and cataloging experience in SW design often not done systematically, or at all Learning how to design starts by studying other designs CSCE 431 OO Design Patterns

22 Characterizing Design Patterns Reusable designs Capturing design knowledge that Is too “high-level” to write as an abstraction in a library What is too high-level depends on the language, of course Modifiable abstractions/designs Basic idea: avoid “re-inventing the wheel” Capture well-tested solutions to oft-occurring situations Modularize design! CSCE 431 OO Design Patterns

23 Design Pattern 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. Visually pleasing and practical structures for an application and/or setting could be described by a pattern language. - Christopher Alexander For example, desirable farmhouses in the Bernese Oberland area of Switzerland used these patterns: North-South AxisGarden to the South West-Facing Entrance Down the SlopePitched Roof Two FloorsHalf-Hipped End Hay Loft at the BackBalcony Toward the Garden Bedrooms in FrontCarved Ornaments CSCE 431 OO Design Patterns

24 Patterns in Software OOPSLA 1987, Kent Beck and Ward Cunningham, Using Pattern Languages for Object-Oriented Programs Applied Alexander’s pattern language to UI design Window Per Task Few Panes Per Window Standard Panes Short Menus Nouns and Verbs More work followed, culminating to the Design Patterns book in 1995 CSCE 431 OO Design Patterns

25 GoF Book CSCE 431 OO Design Patterns

26 23 Patterns in GoF Book CreationalStructuralBehavioral Factory MethodAdapterCommand Abstract FactoryFaçadeVisitor PrototypeProxyIterator BuilderDecoratorInterpreter SingletonCompositeMediator FlyweightMemento BridgeObserver Strategy Template Method Chain of Responsibility State CSCE 431 OO Design Patterns

27 Creational Patterns BuilderSeparates construction from representation (how to build, e.g., Composite objects) Factory methodCreate objects without hardcoding the class name Abstract FactoryGroups factories with a common theme PrototypeCloning from prototypes SingletonRestricts objects to no more than one instance, with a single point of access CSCE 431 OO Design Patterns

28 Structural Patterns AdapterCreates a new interface for an existing unmodifiable interface BridgeSeparates an abstraction form its implementation Composite Tree structure of objects that allows uniform manipulation DecoratorDynamically extensible behavior (instead of statically, as with subclassing) FaçadeUnified interface to simplify use (wrap APIs, etc.) FlyweightShare similar data among many objects ProxyA class serving as a placeholder, possibly adding functionality, to another class CSCE 431 OO Design Patterns

29 Behavioral Patterns Chain of ResponsibilityDelegate command objects to a chain of processing objects CommandWrap a command into an object with all the information that is needed to execute it InterpreterHow to interpret ASTs represented as Composite Objects IteratorAccess objects sequentially without exposing the underlying representation MediatorEncapsulate, and restrict the form of, communication between objects into a dedicated middleman MementoUndo functionality ObserverPublish/subscribe StateObject behavior changes when state changes (modes) StrategySelect most suitable algorithm at runtime Template methodAlgorithm skeleton, with subclasses providing concrete behavior VisitorSeparate algorithm from structure of the object it operates on (double dispatching) CSCE 431 OO Design Patterns

30 Structure of a Design Pattern Four elements A unique name A problem description Situations in which the pattern applies Problems addressed A solution Stated as a set of collaborating classes and interfaces Often uses class diagrams, sequence diagrams, state charts, etc. A set of consequences that describes the trade- offs and alternatives w.r.t. the design goals the pattern addresses CSCE 431 OO Design Patterns

31 GoF Book’s Pattern Structure Pattern Name and Classification Intent “Why use this pattern?” Also known as Motivation (Forces) Often an example scenario Applicability Structure Often class and interaction diagrams Participants Classes and objects involved, and their roles Collaborations How classes/objects interact Consequences Implementation Sample Code Concrete example of how to use the pattern (in code) Known Uses Related Patterns CSCE 431 OO Design Patterns

32 Composite Pattern: Motivation There are times when a program needs to manipulate a tree data structure and it is necessary to treat both Branches as well as Leaf Nodes uniformly. Consider for example a program that manipulates a file system. A file system is a tree structure that contains Branches which are Folders as well as Leaf nodes which are Files. Note that a folder object usually contains one or more file or folder objects and thus is a complex object where a file is a simple object. Note also that since files and folders have many operations and attributes in common, such as moving and copying a file or a folder, listing file or folder attributes such as file name and size, it would be easier and more convenient to treat both file and folder objects uniformly by defining a File System Resource Interface. CSCE 431 OO Design Patterns

33 Composite Pattern: Intent The intent of this pattern is to compose objects into tree structures to represent part-whole hierarchies Composite lets clients treat individual objects and compositions of objects uniformly CSCE 431 OO Design Patterns

34 Composite Pattern: Implementation & Participants ComponentComponent is the abstraction for leafs and composites. It defines the interface that must be implemented by the objects in the composition. For example a file system resource defines move, copy, rename, and getSize methods for files and folders. LeafLeafs are objects that have no children. They implement services described by the Component interface. For example a file object implements move, copy, rename, as well as getSize methods which are related to the Component interface. CompositeA Composite stores child components in addition to implementing methods defined by the component interface. Composites implement methods defined in the Component interface by delegating to child components. In addition composites provide additional methods for adding, removing, as well as getting components. ClientThe client manipulates objects in the hierarchy using the component interface. A client has a reference to a tree data structure and needs to perform operations on all nodes independent of the fact that a node might be a branch or a leaf. The client simply obtains reference to the required node using the component interface, and deals with the node using this interface; it doesn’t matter if the node is a composite or a leaf. CSCE 431 OO Design Patterns

35 Composite Pattern: Applicability The composite pattern applies when there is a part-whole hierarchy of objects and a client needs to deal with objects uniformly regardless of the fact that an object might be a leaf or a branch CSCE 431 OO Design Patterns

36 Example – Graphics Drawing Editor In graphics editors a graphic can be basic or complex. Examples of simple graphics are lines and circles, where a complex graphic is a picture containing many simple (or complex) graphics. Since simple and complex shapes have operations in common, such as rendering the graphic to a screen, and since graphics follow a part-whole hierarchy, composite pattern can be used to enable the program to deal with all graphics uniformly. CSCE 431 OO Design Patterns

37 Example – Graphics Drawing Editor In the example we can see the following actors: Graphic (Component)Graphic is the abstraction for Line, Circle, etc. objects, (leafs) and Picture objects (composites). Line, Circle (Leafs)Objects that have no children. They implement services described by the Graphic interface. Picture (Composite)A Composite stores child Graphic objects in addition to implementing methods defined by the Graphic interface. ClientThe Client (such as a graphical editor) manipulates Graphics in the hierarchy. CSCE 431 OO Design Patterns

38 Composite Pattern: Alternative Implementation Some methods only make sense for Composite objects, such as Add, Remove, and getChild, and in the class diagram above are thus only defined for Composite objects. Prior to calling these methods, one has to cast a Component to a Composite. Alternatively, these methods could be defined in Component, with default implementations that would do nothing. CSCE 431 OO Design Patterns

39 Composite Pattern: Consequences The composite pattern defines class hierarchies consisting of primitive objects and composite objects. Primitive objects can be composed into more complex objects, which in turn can be composed. Clients treat primitive and composite objects uniformly through a component interface which makes client code simple. Adding new components can be easy and client code does not need to be changed since client deals with the new components through the component interface. CSCE 431 OO Design Patterns

40 Composite Pattern: Related Patterns Decorator Pattern Decorator is often used with Composite. When decorators and composites are used together, they will usually have a common parent class. So decorators will have to support the Component interface with operations like Add, Remove, and GetChild. CSCE 431 OO Design Patterns

41 Composite Pattern: Known Uses File system implementation as discussed previously Graphics editors as discussed previously CSCE 431 OO Design Patterns

42 Observations Design patterns make use of interfaces, information hiding, polymorphism, indirection A pattern typically consists of several classes that may have complex associations Design patterns can thus make a design more complex, and decrease performance The tradeoff between added complexity and the potential pay-offs (modularity, extensibility, portability, etc.) needs to be considered CSCE 431 OO Design Patterns

43 Outline Context Some key concepts and notions of OO Design patterns A few more design patterns Idioms Summary CSCE 431 OO Design Patterns

44 Factory Method Intent Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses. Defining a virtual constructor. The new operator considered harmful. CSCE 431 OO Design Patterns

45 Example Problem A framework needs to standardize the architectural model for a range of applications, but allow for individual applications to define their own domain objects and provide for their instantiation. CSCE 431 OO Design Patterns

46 Visitor Pattern Intent Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates. The classic technique for recovering lost type information. Do the right thing based on the type of two objects. Double dispatch Problem Many distinct and unrelated operations need to be performed on node objects in a heterogeneous aggregate structure. You want to avoid “polluting” the node classes with these operations. And, you do not want to have to query the type of each node and cast the pointer to the correct type before performing the desired operation. CSCE 431 OO Design Patterns

47 Visitor Pattern A “static” class hierarchy, possibly tree-like, expressed using the Composite Pattern Each class in this hierarchy defines an accept(visitor&) method accept methods send this pointer to the visitor visitor abstract base class containing visit(a) overload for each class a in the static hierarchy Each derived class of visitor implements some of the visit() overloads Traversal pattern can be either fixed in the accept methods, or left to be expressed in the visit methods CSCE 431 OO Design Patterns

48 Visitor Pattern: Class Diagram CSCE 431 OO Design Patterns

49 Visitor Pattern: Sequence Diagram CSCE 431 OO Design Patterns

50 Outline Context Some key concepts and notions of OO Design patterns A few more design patterns Idioms Summary CSCE 431 OO Design Patterns

51 Idioms Expression of a simple task that is not built-in into a language Pimpl-idiom class Handle { private : class Body * pimpl ; // opaque pointer // Body forward - declared }; Also: a non-obvious use of a particular feature of a language for (;;) { action (); } CSCE 431 OO Design Patterns

52 Idioms Like design patterns, but Language dependent Usually of smaller scope CSCE 431 OO Design Patterns

53 Example: RAll “Resource Acquisition is Initialization” One description in pattern form: From Kevlin Henney, Execute-Around Object. C++ Patterns: Executing Around Sequences. EuroPLoP 2000: Define a helper object that executes actions before and after a sequence of statements in its constructor(s) and destructor. Example: Critical Sections CSCE 431 OO Design Patterns

54 RAII Example class mutex { public : void lock (); void unlock ();... } resource shared ; mutex quard ; guard.lock ();.... // use shared guard.unlock (); CSCE 431 OO Design Patterns  Exception! guard. lock (); try {... // use shared } catch (...) { guard.unlock (); throw ; } guard.unlock ();

55 RAII Example class mutex { public : void lock (); void unlock ();... } resource shared ; mutex quard ; guard.lock ();.... // use shared guard.unlock (); CSCE 431 OO Design Patterns  Exception! template class locker { public : locker ( lockee &to_lock ) : target ( to_lock ) { target.lock (); } ~locker () { target.unlock (); } private : lockee & target ; }; { locker critical ( guard );... // use shared } // destructor called

56 Language Specificity of RAII Not directly expressible in several other OO languages E.g., no destructors in Java, and unclear if and when Java’s finalizers are executed OTOH, Java has its finally construct to handle both normal and exceptional control flows try { // resources acquired actions (); } finally { // resources released } CSCE 431 OO Design Patterns

57 Outline Context Some key concepts and notions of OO Design patterns A few more design patterns Idioms Summary CSCE 431 OO Design Patterns

58 Meta-Taxonomy of Patterns TypeDescriptionExamples IdiomsSmall scale, language/ tool/system specificRAII. Scoped locking. Design patternsStatic and dynamic roles and relationships in oft-occurring designs. Bridge. Composite. Visitor. Architectural patternsStructural organization of software systems. Set of predefined subsystems and their relationships. Rules and guidelines for organizing the relationships between them. Publisher- Subscriber. Pipes and Filters. Optimization principlesAvoid common design/ implementation mistakes that degrade performance Optimize for common case. AntipatternsCommonly used pattern that is counterproductive Lava Flow. Copy and Paste. Code smellsCharacterizations of suspicious code. Similar to antipatterns, but less formal Long Method. Indecent Exposure. CSCE 431 OO Design Patterns

59 Are design pattern something fundamentally different from what existed before? B. Meyer: new ideas are often met with a sequence of three reactions: 1.There is nothing to it 2.It will never work 3.That is how we have always done it Relating to patterns: 1.Is the notion of a design pattern a significant idea? 2.Do they really work? 3.What is new about describing solutions to problems? Maybe new is: systematic approach recognizing that abstractions that cannot quite be packaged into libraries/modules can still be reusable and reused provides a vocabulary for discussing software development problems CSCE 431 OO Design Patterns

60 PLoP 2012 There are devoted people: PLoP 2012: 19th CONFERENCE ON PATTERN LANGUAGES OF PROGRAMS CSCE 431 OO Design Patterns

61 PLoP Pattern Languages of Programs (PLoP TM ) conference is a premier event for pattern authors and pattern enthusiasts to gather, discuss and learn more about patterns and software development. The purpose of PLoP is to: promote development of pattern languages, primarily about aspects of software: design and programming, testing, software architecture, user interface design, domain modelling, and software processes. Patterns and pattern languages for domains outside software are also welcome CSCE 431 OO Design Patterns

62 TPLoP CSCE 431 OO Design Patterns


Download ppt "CSCE 431: (Object Oriented) Design Patterns Some material from R. Martin, Bruegge, Dutoit."

Similar presentations


Ads by Google