Presentation is loading. Please wait.

Presentation is loading. Please wait.

Traditional Design Patterns -- II

Similar presentations


Presentation on theme: "Traditional Design Patterns -- II"— Presentation transcript:

1 Traditional Design Patterns -- II
These slides are mainly based on: Tutorial slides by John Vlissides, see and Text © by Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides Diagrams © 1995 by Addison-Wesley Publishing Company Note: Compared to the original tutorial by John Vlissides, the diagram notation have been upgraded from OMT to UML and some text has been updated

2 Overview Example: WYSIWYG Editor (Cont'd) Some more patterns
Spelling checking & hyphenation Iterator Visitor Some more patterns Template Method Singleton Façade Observations and Conclusions Further reading

3 Iterator (Behavioral)
Intent Access elements of an aggregate sequentially without exposing its representation Applicability Require multiple traversal algorithms over an aggregate Require a uniform traversal interface over different aggregates When aggregate classes and traversal algorithm must vary independently © E. Gamma, R. Helm, R. Johnson, J. Vlissides and Addison-Wesley

4 Iterator (cont'd) Structure
© E. Gamma, R. Helm, R. Johnson, J. Vlissides and Addison-Wesley

5 Iterator Examle import java.util.*; class IntSet {
private Hashtable ht = new Hashtable(); public static class Iterator { private IntSet set; private Enumeration e; private Integer current; public Iterator( IntSet in ) { set = in; } public void first() { e = set.ht.keys(); next(); } public boolean isDone() { return current == null; } public int currentItem() { return current.intValue(); } public void next() { try { current = (Integer) e.nextElement(); } catch (NoSuchElementException e) { current = null; } } public void add( int in ) { ht.put( new Integer( in ), "null" ); } public boolean isMember( int i ) { return ht.containsKey(new Integer(i)); } public Hashtable getHashtable() { return ht; } public Iterator createIterator() { return new Iterator( this ); }

6 Iterator Example class IteratorDemo {
public static void main( String[] args ) { IntSet set = new IntSet(); ………. // Code to add elements to the set and other code // Clients ask the collection object to create many iterator objects IntSet.Iterator it1 = set.createIterator(); IntSet.Iterator it2 = set.createIterator(); // Clients use the first(), isDone(), next(), currentItem() protocol System.out.print( "\nIterator: " ); for ( it1.first(), it2.first(); ! it1.isDone(); it1.next(), it2.next() ) System.out.print( it1.currentItem() + " " + it2.currentItem() + " " ); System.out.print( "\nEnumeration: " ); for (Enumeration e = set.getHashtable().keys(); e.hasMoreElements(); ) System.out.print( e.nextElement() + " " ); System.out.println(); }

7 Iterator (cont'd) Consequences Implementation Known Uses
Flexibility: aggregate and traversal are independent Multiple iterators  multiple traversal algorithms Additional communication overhead between iterator and aggregate Implementation Internal versus external iterators Violating the object structure's encapsulation Robust iterators Known Uses Penpoint traversal driver/slave InterViews ListItr Unidraw Iterator © E. Gamma, R. Helm, R. Johnson, J. Vlissides and Addison-Wesley

8 Overview Example: WYSIWYG Editor (Cont'd) Some more patterns
Spelling checking & hyphenation Iterator Visitor Some more patterns Template Method Singleton Façade Observations and Conclusions Further reading

9 Visitor (Behavioral) Intent Applicability
Centralize operations on an object structure so that they can vary independently but still behave polymorphically Applicability When classes define many unrelated operations Class relationships of objects in the structure rarely change, but the operations on them change often Algorithms over the structure maintain state that's updated during traversal © E. Gamma, R. Helm, R. Johnson, J. Vlissides and Addison-Wesley

10 Visitor (cont'd) Consequences Implementation Known Uses
Flexibility: visitor and object structure are independent Localized functionality Circular dependency between Visitor and Element interfaces Visitor brittle to new ConcreteElement classes Implementation Double dispatch Overloading visit operations Catch-all operation General interface to elements of object structure Known Uses ProgramNodeEnumerator in Smalltalk-80 compiler IRIS Inventor scene rendering © E. Gamma, R. Helm, R. Johnson, J. Vlissides and Addison-Wesley

11 Visitor (cont'd) Structure
© E. Gamma, R. Helm, R. Johnson, J. Vlissides and Addison-Wesley

12 Example—A Printing Visitor
public class SomeContainer implements Container { public void accept (Visitor visitor) { for each Object i in this container{ visitor.visit (i); if (visitor.isDone(this)) break; } } // ... } public class PrintingVisitor extends AbstractVisitor { public void visit (Object object) { System.out.println (object); } // ... } // // in another class... Container c = new SomeContainer (); // ... c.accept (new PrintingVisitor ()); Definition of SomeContainer and of the accept method Use of visitor

13 Editor Example – Summary
Document Structure Composite Formatting Strategy Embellishment Decorator Multiple Look&Feels Abstract Factory (Multiple window systems) Bridge (User operations) Command Spelling checking & hyphenation Iterator & Visitor

14 Overview Example: WYSIWYG Editor (Cont'd) Some more patterns
Spelling checking & hyphenation Iterator Visitor Some more patterns Template Method Singleton Façade Observations and Conclusions Further reading

15 Template Method (Behavioral)
Intent Define the skeleton of an algorithm in an operation, deferring some steps to subclasses Applicability To implement invariant aspects of an algorithm once and let subclasses define variant parts To localize common behavior in a class to increase code reuse To control subclass extensions © E. Gamma, R. Helm, R. Johnson, J. Vlissides and Addison-Wesley

16 Template Method (cont'd)
Structure © E. Gamma, R. Helm, R. Johnson, J. Vlissides and Addison-Wesley

17 Template Method (cont'd)
Consequences Leads to inversion of control (“Hollywood principle”: don't call us – we'll call you) Promotes code reuse Lets you enforce overriding rules Must subclass to specialize behavior Implementation Virtual vs. non-virtual template method Few vs. lots of primitive operations Naming conventions (do- prefix) Known Uses Just about all object-oriented systems (especially frameworks) © E. Gamma, R. Helm, R. Johnson, J. Vlissides and Addison-Wesley

18 Template Method (cont'd)
Typical implementation: public abstract class Node { public final void streamOut (OutputStream out) { if (isReadable()) { doStreamOut(out); } else { doWarning(unreadableWarning); } // ... isReadable, doStreamOut, and doWarning are primitive operations © E. Gamma, R. Helm, R. Johnson, J. Vlissides and Addison-Wesley

19 Template Method - Example

20 Template Method - Example
class JuniorAccount : public Account     {      public:          void virtual TransactionSubpartA();     } class SavingsAccount : public Account     {      public:          void virtual TransactionSubpartC();     } // Client code Account*  customer; customer = JunionAccount(); customer->Transaction(amount); class Account     {      public:           void Transaction(float amount);           void virtual TransactionSubpartA();           void virtual TransactionSubpartB();           void virtual TransactionSubpartC();     } void Account::Transaction(float amount)     {      TransactionSubpartA();      TransactionSubpartB();      TransactionSubpartC();     // EvenMoreCode;     }

21 Singleton (Creational)
Intent Ensure a class only ever has one instance, and provide a global point of access to it. Applicability When there must be exactly one instance of a class, and it must be accessible from a well-known access point When the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code © E. Gamma, R. Helm, R. Johnson, J. Vlissides and Addison-Wesley

22 Singleton (cont'd) Structure
© E. Gamma, R. Helm, R. Johnson, J. Vlissides and Addison-Wesley

23 Singleton (cont'd) Consequences Implementation
Reduces namespace pollution Makes it easy to change your mind and allow more than one instance Allow extension by subclassing Same drawbacks of a global if misused Implementation may be less efficient than a global Concurrency pitfalls Implementation Static instance operation Registering the singleton instance © E. Gamma, R. Helm, R. Johnson, J. Vlissides and Addison-Wesley

24 Singleton (cont'd) Known Uses Unidraw's Unidraw object
Smalltalk-80 ChangeSet, the set of changes to code InterViews Session object © E. Gamma, R. Helm, R. Johnson, J. Vlissides and Addison-Wesley

25 Singleton - Example class Singleton { public:
static Singleton* Instance(); protected: Singleton(); Singleton(const Singleton&); Singleton& operator= (const Singleton&) private: static Singleton* pinstance; }; Singleton* Singleton::pinstance = 0; // initialize pointer Singleton* Singleton::Instance () { if (pinstance == 0) // is it the first call? { pinstance = new Singleton; // create sole instance } return pinstance; // address of sole instance Singleton::Singleton() { //... perform necessary instance initializations

26 Singleton - Example Although the above example uses a single instance,
// Client code Singleton *p1 = Singleton::Instance(); Singleton *p2 = p1->Instance(); Singleton & ref = * Singleton::Instance(); Although the above example uses a single instance, modifications to the function Instance() may permit a variable number of instances. For example, you can design a class that allows up to three instances.

27 Overview Example: WYSIWYG Editor (Cont'd) Some more patterns
Spelling checking & hyphenation Iterator Visitor Some more patterns Template Method Singleton Façade Observations and Conclusions Further reading

28 Façade Façade © E. Gamma, R. Helm, R. Johnson, J. Vlissides and Addison-Wesley

29 Façade

30 Façade - Example

31 Overview Example: WYSIWYG Editor (Cont'd) Some more patterns
Spelling checking & hyphenation Iterator Visitor Some more patterns Template Method Singleton Façade Observations and Conclusions Further reading

32 Inheritance vs. Object Composition
Provides for clean separation between components through interfaces Allows for dynamic composition Allows for flexible mixing and matching of features Has the overhead of forwarding Suffers from the identity crisis Leads to more fragmentation Inheritance No explicit forwarding necessary Close coupling between a class and its base class Inheritance hierarchies are static and cannot be reconfigured at runtime Adding features through subclassing may lead to a combinatorial explosion Beware of overusing inheritance–inheritance is not always the best choice Deep inheritance hierarchy (6 levels and more) in your application is a red flag

33 Implementation vs. interface inheritance
Implementation inheritance – inheriting implementation of methods Is a convenient reuse mechanism, but… Introduces high coupling Changing a superclass may brake all subclasses (“fragile base class problem”) Interface inheritance – inheriting interface but no implementation (e.g., inheritance involving abstract classes in C++ and interfaces in Java) Does not suffer from the problems of implementation inheritance Subtyping and interface inheritance are more important than implementation inheritance Consider declaring the type of variables to be interfaces rather than concrete classes

34 OO Frameworks A framework consists of a set of cooperating classes embodying a design for a family of applications. There are different categories of frameworks: White-box frameworks are reused by subclassing, which usually requires understanding the implementation of the framework to some degree Template method is one of the main mechanisms for white-box frameworks Black-box framework is reused by parameterizing and assembling framework objects. Black-box frameworks hide their implementation from their users Black-box frameworks make heavy use of patterns based on object composition such as decorator and strategy. Many practical frameworks fall somewhere between the white-box and black-box categories

35 Patterns at Different Levels
Applicable in most stages of the OO lifecycle Analysis, design, implementation, reviews, documentation, reuse, and refactoring Analysis patterns Typical solutions to recuring anlysis problems See Analysis Patterns, Fowler; Addison-Wesley, 1996 Architectural patterns See POSA Design patterns Most GoF design patterns are applicable both at the architectural and detailed design Idioms Smalltalk Best Practice Patterns, Beck; Prentice Hall, 1997 Concurrent Programming in Java, Lea; Addison-Wesley, 1997 Advanced C++, Coplien, Addison-Wesley, 1992 Effective C++: 50 Specific Ways to Improve Your Programs and Design (2nd Edition), Scott Meyers, Addison-Wesley, (September 1997) More Effective C++: 35 New Ways to Improve Your Programs and Designs, Scott Meyers, Addison-Wesley (December 1995)

36 Observations Patterns permit design at a more abstract level
Treat many class/object interactions as a unit Often beneficial after initial design Targets for class refactorings Variation-oriented design Consider what design aspects are variable Identify applicable pattern(s) Vary patterns to evaluate tradeoffs Repeat


Download ppt "Traditional Design Patterns -- II"

Similar presentations


Ads by Google