CS 501 Introduction to Design Patterns Nate Nystrom Eric Melin November 9, 1999

  • Published on

  • View

  • Download

Embed Size (px)


<ul><li> Slide 1 </li> <li> CS 501 Introduction to Design Patterns Nate Nystrom Eric Melin November 9, 1999 </li> <li> Slide 2 </li> <li> Motivation Designing reusable software is hard usually impossible to get right the first time takes several uses of a design to get it right Experts base new designs on prior experience In many systems, you find recurring patterns of software components classes, protocols, etc. </li> <li> Slide 3 </li> <li> Design patterns Idea: extract these common patterns and create a catalog of design patterns allows other designers to reuse successful designs and avoid unsuccessful ones creates a common vocabulary for discussing designs 1995: Design Patterns book by the Gang of Four (Gamma, Helm, Johnson, Vlissides) describes 21 common patterns </li> <li> Slide 4 </li> <li> What is a design pattern? A pattern has four components: A name A problem A solution Consequences </li> <li> Slide 5 </li> <li> Name Immediately allows you to design at a higher level of abstraction Allows you to discuss the pattern with others </li> <li> Slide 6 </li> <li> Problem What problem does the pattern solve? When do you apply the pattern? </li> <li> Slide 7 </li> <li> Solution Elements that make up the design Relationships, responsibilities, collaborations NOT a particular concrete design or implementation A pattern is a template that can be applied in many different situations </li> <li> Slide 8 </li> <li> Consequences Results and trade-offs of applying the pattern Impact on system's flexibility, extensibility, portability </li> <li> Slide 9 </li> <li> What is not a design pattern? A design of a data structure A domain-specific design A design of an entire application A design used only once A design pattern should capture mature, proven practices </li> <li> Slide 10 </li> <li> Classifying design patterns GoF identified two criteria for classifying design patterns Purpose Scope </li> <li> Slide 11 </li> <li> Purpose Creational patterns describe how objects are created Structural patterns describe the composition of classes or objects Behavioral patterns describe the interaction of classes or objects and how responsibility is distributed </li> <li> Slide 12 </li> <li> Scope Class patterns Deal with relationships between classes and their subclasses Object patterns Deal with relationships between objects Relationships can change at run-time and are thus more dynamic </li> <li> Slide 13 </li> <li> Non-OO design patterns Design patterns are not limited to object- oriented software Objects are just one way to partition a system, sometimes not the best way You will find many more mature patterns in legacy systems than you will in OO software </li> <li> Slide 14 </li> <li> Before Patterns: Motorola Factors preventing software reuse Strong coupling of classes/objects Short-term needs superseded longer-term Architecture specifications suffered from Ambiguity and lack of precision in the specs Differing terminology No direct access to the architects </li> <li> Slide 15 </li> <li> Review of OO concepts OO programs are made up of objects An object packages both data and operations on that data An object's operations are called methods An object's implementation is defined by its class New classes can be defined using existing classes through inheritance </li> <li> Slide 16 </li> <li> Encapsulation In pure OO: method invocations (messages) are the only way an object can execute an operation The object's internal state is encapsulated Encapsulation is often violated for efficiency </li> <li> Slide 17 </li> <li> Polymorphism Different objects can handle identical messages with different implementations Dynamic binding: Run-time association of a message to an object and one of the object's operations Can substitute objects that implement the same interface at run-time </li> <li> Slide 18 </li> <li> Inheritance There is a distinction between an object's class and its type Class defines how an object is implemented Type defines the object's interface Java thus defines two forms of inheritance Implementation inheritance Ex: class B extends A { m() {} } Interface inheritance Ex: class C implements I { m() {} } </li> <li> Slide 19 </li> <li> Reuse through subclassing Easier to modify the implementation being reused But, breaks encapsulation Implementation of the subclass bound to that of the parent any change to the parent requires change to the subclass Must reimplement parent if any aspect of the its implementation is not appropriate to the new context in which it is used </li> <li> Slide 20 </li> <li> Reuse through composition (1) Requires carefully designed interfaces Doesnt break encapsulation Any object can be replaced by another at run- time if it implements the same interface Fewer implementation dependencies Helps design keeping each class encapsulated forces you to keep classes simple </li> <li> Slide 21 </li> <li> Reuse through composition (2) But, composition leads to more objects in the system Behavior depends on interrelationships between many objects not on one class </li> <li> Slide 22 </li> <li> GoFs Principles of OO design Program to an interface, not an implementation Favor composition over inheritance Ideally, get all the functionality you need by composing existing components In practice, available components arent rich enough Reuse by inheritance easier to create new components that can be composed of old ones </li> <li> Slide 23 </li> <li> Summary Patterns are a good team communication medium are extracted from working designs capture the essential parts of a design in compact form can be used to record and encourage the reuse of "best practices" are not necessarily object-oriented </li> <li> Slide 24 </li> <li> The Iterator pattern Provides a way to access elements of an aggregate object without exposing the underlying representation Ex: a List class Want to traverse the list in several ways forward backward filtered sorted ... </li> <li> Slide 25 </li> <li> Motivation for iterators Don't want to bloat the List interface with several different traversals Even if you do, you can't anticipate all the possible traversals Might want &gt;1 traversal on the same list Iterator moves responsibility for access and traversal from the aggregate to an iterator object </li> <li> Slide 26 </li> <li> Iterator example (1) class List { size() {} add() {} remove() {} } interface ListIterator { getFirst(); getNext(); } </li> <li> Slide 27 </li> <li> Iterator example (2) class FilteredListIterator implements ListIterator { List.Node curr; FilteredListIterator(List list, Filter f) {} getFirst() { curr = list.head; while (curr != null) { if (f.accepts(curr.data)) break; curr = curr.next; } return curr; } getNext() {} } </li> <li> Slide 28 </li> <li> More on the Iterator pattern Iterators provide a common interface for accessing aggregates Can use the same interface for lists implemented as arrays and lists implements as linked lists Easier to change data structure implementations See java.util in JDK 1.2 for good examples </li> <li> Slide 29 </li> <li> The Visitor pattern Represent an operation to be performed on the elements of an object structure Lets you defined a new operation without changing the classes of the elements on which it operates </li> <li> Slide 30 </li> <li> Visitor example: a compiler Consider a compiler that represents a program as an abstract syntax tree Need to perform operations on the AST type checking optimization code generation </li> <li> Slide 31 </li> <li> Example AST for (i = 0; i &lt; 100; i++) { t = f(i,true); a[i] = t; } </li> <li> Slide 32 </li> <li> Design 1 Operations treat nodes of different types differently Ex: code generated for assignments is different than code generated for calls Proposed design: add a method to each node class to perform a particular operation on that node type </li> <li> Slide 33 </li> <li> Design 1 example class Assign { genCode() {} typeCheck() {} optimize() {} } class Call { genCode() {} typeCheck() {} optimize() {} } </li> <li> Slide 34 </li> <li> Problem with Design 1 Every time we add or modify an operation, we have to change the class for each node type Ex: one Java bytecode analyzer has 61 different node types </li> <li> Slide 35 </li> <li> Design 2 Better solution: Put each operation in a different class called a visitor Works well if we assume adding new node types is uncommon We have to update all the visitors when a new node type is added </li> <li> Slide 36 </li> <li> Design 2 example (1) interface ASTVisitor { visitAssign(Assign a); visitCall(Call c);... } class Assign { Exp left; Exp right;... accept(ASTVisitor v) { left.accept(v); right.accept(v); v.visitAssign(this); } </li> <li> Slide 37 </li> <li> Design 2 example (2) class TypeCheckVisitor implements ASTVisitor { visitAssign(Assign a) { Type ltype = a.getLeft().getType(); Type rtype = a.getRight().getType(); if (! Ltype.isSuperOf(rtype)) { errors.add(...); }... } </li> <li> Slide 38 </li> <li> Creational and Structural Patterns Creational Encapsulate knowledge about which concrete classes the system uses Hide how instances of these classes are created and put together Examples: Singleton, Abstract Factory Structural Describe how classes and objects are composed into larger structures Examples: Proxy, Faade, Composite </li> <li> Slide 39 </li> <li> Singleton Motivation Some classes need exactly one instance One window manager, one file system, one print spooler Need global access, but global variable does not prevent multiple instantiation Have class keep track of its sole instance Intent Ensure a class has only one instance and provide a global point of access </li> <li> Slide 40 </li> <li> Singleton (2) Applicability There must be exactly one instance of a class and it must be accessible to multiple clients The sole instance should be extensible by subclassing, and clients should be able to use subclass without modifying code Consequences Controlled access to sole instance Reduced name space (over global variable) Extendable implementation Permits a variable number of instances (easy to change if dont want singleton) More flexible than static member functions allows subclassing and easy to change to multiple number of instances </li> <li> Slide 41 </li> <li> Abstract Factory Intent Provide an interface for creating families of related objects without specifying their concrete classes Example of Abstract Product and Concrete Products </li> <li> Slide 42 </li> <li> Abstract Factory (2) </li> <li> Slide 43 </li> <li> Abstract Factory (3) Applicability A system should be independent of how its products are created, composed, and represented A system should be configured with multiple families of products Need to enforce constraint a family of related product objects should be glued together Want to provide library of products and reveal only their interfaces </li> <li> Slide 44 </li> <li> Abstract Factory (4) Consequences Concrete classes are isolated to concrete factory Allows easy exchanging of product families Promotes consistency amongst products It is hard to add new types of products </li> <li> Slide 45 </li> <li> Proxy A proxy provides a placeholder for another object to access it </li> <li> Slide 46 </li> <li> Proxy (2) Structure The proxy has the same interface or superclass as the real subject The proxy contains a reference to real subject which the proxy can use to forward requests to the real subject Applicability A remote proxy acts as a local representation for a remote object A virtual proxy creates expensive objects on demand Example a proxy for a graphical image when image is not on screen A protection proxy controls access to the original object A firewall proxy protects local clients from outside world A cache proxy (server proxy) saves network resources by storing results Smart Reference Example - garbage collector reference counter (Smart Pointers) </li> <li> Slide 47 </li> <li> Proxy (3) Consequences Proxy introduces a level of indirection. Remote proxy can hide fact that object resides elsewhere Copy-on-write is possible this is a significant optimization for heavy-weight components </li> <li> Slide 48 </li> <li> Faade Intent - provide a unified interface to a set of interfaces in a subsystem </li> <li> Slide 49 </li> <li> Faade (2) Motivation Structuring a system into subsystems reduces complexity Want to reduce communications and dependencies between subsystems Applicability Want to provide a simple interface to a complex subsystem There are many dependencies between clients and implementation classes in a subsystem. Want to decouple the subsystem from clients and other subsystems Want to layer subsystems Can use a faade to define entry point to each subsystem level </li> <li> Slide 50 </li> <li> Faade (3) Consequences Faade reduces the number of objects that clients deal with to make the subsystem easier to use Promotes weak coupling between subsystem and clients. This allows you to change subsystem implementation without affecting clients Allows clients to use subsystem classes if they need to Subsystem components are not aware of faade </li> <li> Slide 51 </li> <li> Comparison of Patterns Proxy vs. Faade A facade represents a system of objects A proxy represents a single object A facade simplifies the interact between client and the system A proxy controls the access to the single object </li> <li> Slide 52 </li> <li> Composite Compose objects into tree structures to let clients treat individual objects and compositions of objects uniformly </li> <li> Slide 53 </li> <li> Composite (2) </li> <li> Slide 54 </li> <li> Composite (3) Motivation How does a window hold and deal with the different items it has to manage? Graphics - Containers and widgets Panel, Menu, Window Line, Rectangle, Text Cut And Paste </li> <li> Slide 55 </li> <li> Composite (4) Applicability Want to represent part-whole hierarchies of objects Want clients to be able to ignore the difference between compositions of objects and individual objects. Consequences Whenever client code expects a primitive object, it can also receive a composite object Makes the client simple Facilitates adding of new components Can make design overly general makes it hard to restrict the components of a composite </li> <li> Slide 56 </li> <li> Composite Implementation Issues Explicit parent references Sharing parents wasteful not to, but need ability for child to have multiple parents Maximize Component interface Component should define as many common operations as possible Child management operations are tricky Can define child management operations in Component Class (root of hierarchy) Unsafe - What does adding a child to a leaf node mean? Can define child management in Composite class Safety, but Now downcasts or instanceof checks into components and leaves are necessary </li> <li> Slide 57 </li> <li> References Design Patterns: Elements of Reusable Object-Oriented Software, Gamma, Helm, Johnson, Vlissides, Addison Wesley, 1995, pp 207- 217 http://www.eli.sdsu.edu/courses/spring98/cs635/index.html http://st-www.cs.uiuc.edu/cgi-bin/wikic/wikic http://www.tcm.hut.fi/~pnr/GoF-models/html/ </li> </ul>