Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSCE 431: (Object Oriented) Design Patterns

Similar presentations


Presentation on theme: "CSCE 431: (Object Oriented) Design Patterns"— Presentation transcript:

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

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

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

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 CSCE 431 OO Design Patterns
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 CSCE 431 OO Design Patterns
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 CSCE 431 OO Design Patterns
Outline Context Some key concepts and notions of OO Design patterns A few more design patterns Idioms Summary CSCE 431 OO Design Patterns

8 CSCE 431 OO Design Patterns
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 CSCE 431 OO Design Patterns
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 CSCE 431 OO Design Patterns
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 Example invariant: months have 28 to 31 days CSCE 431 OO Design Patterns

12 CSCE 431 OO Design Patterns
Inheritance Where used: 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 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 CSCE 431 OO Design Patterns
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 { @invariant i1; @pre p1; virtual void foo (...); @post q1 } class B : public A { @invariant i2; @pre p2; void foo (...); @post 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” p1  p2 q1  q2 i1  i2 CSCE 431 OO Design Patterns

18 Inheritance vs. Delegation
Consider this inheritance relation: Implementation 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

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 CSCE 431 OO Design Patterns
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 CSCE 431 OO Design Patterns
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 Axis Garden to the South West-Facing Entrance Down the Slope Pitched Roof Two Floors Half-Hipped End Hay Loft at the Back Balcony Toward the Garden Bedrooms in Front Carved Ornaments CSCE 431 OO Design Patterns

24 CSCE 431 OO Design Patterns
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 CSCE 431 OO Design Patterns
GoF Book GoF == Gang of Four == Gamma, Helm, Johnson, Vlissides CSCE 431 OO Design Patterns

26 CSCE 431 OO Design Patterns
23 Patterns in GoF Book Creational Structural Behavioral Factory Method Adapter Command Abstract Factory Façade Visitor Prototype Proxy Iterator Builder Decorator Interpreter Singleton Composite Mediator Flyweight Memento Bridge Observer Strategy Template Method Chain of Responsibility State CSCE 431 OO Design Patterns

27 CSCE 431 OO Design Patterns
Creational Patterns Builder Separates construction from representation (how to build, e.g., Composite objects) Factory method Create objects without hardcoding the class name Abstract Factory Groups factories with a common theme Prototype Cloning from prototypes Singleton Restricts objects to no more than one instance, with a single point of access CSCE 431 OO Design Patterns

28 CSCE 431 OO Design Patterns
Structural Patterns Adapter Creates a new interface for an existing unmodifiable interface Bridge Separates an abstraction form its implementation Composite Tree structure of objects that allows uniform manipulation Decorator Dynamically extensible behavior (instead of statically, as with subclassing) Façade Unified interface to simplify use (wrap APIs, etc.) Flyweight Share similar data among many objects Proxy A class serving as a placeholder, possibly adding functionality, to another class CSCE 431 OO Design Patterns

29 CSCE 431 OO Design Patterns
Behavioral Patterns Chain of Responsibility Delegate command objects to a chain of processing objects Command Wrap a command into an object with all the information that is needed to execute it Interpreter How to interpret ASTs represented as Composite Objects Iterator Access objects sequentially without exposing the underlying representation Mediator Encapsulate, and restrict the form of, communication between objects into a dedicated middleman Memento Undo functionality Observer Publish/subscribe State Object behavior changes when state changes (modes) Strategy Select most suitable algorithm at runtime Template method Algorithm skeleton, with subclasses providing concrete behavior Visitor Separate algorithm from structure of the object it operates on (double dispatching) AST == abstract syntax tree 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
Component Component 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. Leaf Leafs 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. Composite A 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. Client The 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. Client The 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 CSCE 431 OO Design Patterns
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 CSCE 431 OO Design Patterns
Outline Context Some key concepts and notions of OO Design patterns A few more design patterns Idioms Summary CSCE 431 OO Design Patterns

44 CSCE 431 OO Design Patterns
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 CSCE 431 OO Design Patterns
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 CSCE 431 OO Design Patterns
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 CSCE 431 OO Design Patterns
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 CSCE 431 OO Design Patterns
Outline Context Some key concepts and notions of OO Design patterns A few more design patterns Idioms Summary CSCE 431 OO Design Patterns

51 CSCE 431 OO Design Patterns
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 CSCE 431 OO Design Patterns
Idioms Like design patterns, but Language dependent Usually of smaller scope CSCE 431 OO Design Patterns

53 CSCE 431 OO Design Patterns
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 CSCE 431 OO Design Patterns
RAII Example class mutex { public : void lock (); void unlock (); ... } resource shared ; mutex quard ; guard.lock (); .... // use shared guard.unlock (); guard . lock (); try { ... // use shared } catch (...) guard.unlock (); throw ;  Exception! CSCE 431 OO Design Patterns

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

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 CSCE 431 OO Design Patterns
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
Type Description Examples Idioms Small scale, language/ tool/system specific RAII. Scoped locking. Design patterns Static and dynamic roles and relationships in oft-occurring designs. Bridge. Composite. Visitor. Architectural patterns Structural 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 principles Avoid common design/ implementation mistakes that degrade performance Optimize for common case. Antipatterns Commonly used pattern that is counterproductive Lava Flow. Copy and Paste. Code smells Characterizations of suspicious code. Similar to antipatterns, but less formal Long Method. Indecent Exposure. CSCE 431 OO Design Patterns

59 CSCE 431 OO Design Patterns
Are design pattern something fundamentally different from what existed before? B. Meyer: new ideas are often met with a sequence of three reactions: There is nothing to it It will never work That is how we have always done it Relating to patterns: Is the notion of a design pattern a significant idea? Do they really work? 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 CSCE 431 OO Design Patterns
PLoP 2012 There are devoted people: PLoP 2012: 19th CONFERENCE ON PATTERN LANGUAGES OF PROGRAMS CSCE 431 OO Design Patterns

61 CSCE 431 OO Design Patterns
PLoP Pattern Languages of Programs (PLoPTM) 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 CSCE 431 OO Design Patterns
TPLoP CSCE 431 OO Design Patterns


Download ppt "CSCE 431: (Object Oriented) Design Patterns"

Similar presentations


Ads by Google