Patterns & C Object-Oriented Design Case Studies With

2y ago
5 Views
2 Downloads
896.18 KB
73 Pages
Last View : 1m ago
Last Download : 3m ago
Upload by : Angela Sonnier
Transcription

Object-Oriented Design Case Studies withPatterns & C Douglas C. nderbilt.edu/ schmidt/Department of EECSVanderbilt University(615) 343-8197OO Pattern ExamplesDouglas C. SchmidtCase Studies Using Patterns The following slides describe several case studies using C &patterns to build highly extensible software The examples include1. Expression Tree– e.g., Adapter, Factory, Bridge2. System Sort– e.g., Facade, Adapter, Iterator, Singleton, Factory Method,Strategy, Bridge3. Sort Verifier– e.g., Strategy, Factory Method, Facade, Iterator, SingletonVanderbilt University1

OO Pattern ExamplesDouglas C. SchmidtCase Study: Expression Tree Evaluator The following inheritance & dynamic binding example constructsexpression trees– Expression trees consist of nodes containing operators &operands Operators have different precedence levels, different associativities,& different arities, e.g., Multiplication takes precedence over addition The multiplication operator has two arguments, whereas unaryminus operator has only one Operands are integers, doubles, variables, etc. We’ll just handle integers in this example . . .Vanderbilt University2OO Pattern ExamplesDouglas C. SchmidtExpression Tree Diagram*UNARYNODEBINARYNODES 5344INTEGERNODESVanderbilt University3

OO Pattern ExamplesDouglas C. Schmidt4Vanderbilt UniversityExpression Tree Behaviortypedef struct Tree Node Tree Node;struct Tree Node {enum { NUM, UNARY, BINARY } tag ;short use ; /* reference count */union {char op [2];int num ;} o;#define num o.num#define op o.opunion {Tree Node *unary ;struct { Tree Node *l , *r ; } binary ;} c;#define unary c.unary#define binary c.binary};Expression treesA typical algorithmic method for implementingexpression trees involves using a struct/union torepresent data structure, e.g.,– Trees may be “evaluated” via different traversals e.g., in-order, post-order, pre-order, level-order– The evaluation step may perform various operations, e.g., Traverse & print the expression tree Return the “value” of the expression tree Generate codePerform semantic analysis Algorithmic Version DoVanderbilt UniversityOO Pattern Examples

TreeNode11 2TreeNodeDouglas C. SchmidtMemory Layout of Algorithmic VersionOO Pattern Examplestaguseopnumunarybinary6Vanderbilt UniversityCLASSRELATIONSHIPSvoid print tree (Tree Node *root) {switch (root- tag ) {case NUM: printf ("%d", root- num );break;case UNARY:printf ("(%s", root- op [0]);print tree (root- unary );printf (")"); break;case BINARY:printf ("(");print tree (root- binary .l );printf ("%s", root- op [0]);print tree (root- binary .r );printf (")"); break;default:printf ("error, unknown type\n");}}MEMORYLAYOUTA typical algorithmic implementation use a switchstatement & a recursive function to build &evaluate a tree, e.g.,Here’s the memory layout of a struct Tree Node object Print Tree FunctionDoVanderbilt UniversityOO Pattern Examples

OO Pattern ExamplesDouglas C. SchmidtLimitations with Algorithmic Approach Problems or limitations with the typical algorithmic approach include– Little or no use of encapsulation Incomplete modeling of the application domain, which results in1. Tight coupling between nodes & edges in union representation2. Complexity being in algorithms rather than the data structures– e.g., switch statements are used to select between various typesof nodes in the expression trees– Compare with binary search!3. Data structures are “passive” & functions do most processing workexplicitlyVanderbilt UniversityOO Pattern Examples8Douglas C. SchmidtMore Limitations with Algorithmic Approach The program organization makes it difficult to extend, e.g.,– Any small changes will ripple through the entire design &implementation e.g., see the “ternary” extension below– Easy to make mistakes switching on type tags . . . Solution wastes space by making worst-case assumptions wrtstructs & unions– This is not essential, but typically occurs– Note that this problem becomes worse the bigger the size of thelargest item becomes!Vanderbilt University9

OO Pattern ExamplesDouglas C. SchmidtOO Alternative Contrast previous algorithmic approach with an object-orienteddecomposition for the same problem:– Start with OO modeling of the “expression tree” applicationdomain, e.g., go back to original picture– Discover several classes involved: class Node: base class that describes expression tree vertices: class Int Node: used for implicitly converting int to Tree node class Unary Node: handles unary operators, e.g., -10, 10, !a class Binary Node: handles binary operators, e.g., a b, 10 30 class Tree: “glue” code that describes expression-tree edges,i.e., relations between Nodes– Note, these classes model entities in the application domain i.e., nodes & edges (vertices & arcs)Vanderbilt University10OO Pattern ExamplesDouglas C. SchmidtExpression Tree Diagram*UNARYNODEBINARYNODES 5344INTEGERNODESVanderbilt University11

OO Pattern ExamplesDouglas C. SchmidtRelationships Between Tree & Node ode1Tree-ahasVanderbilt UniversityOO Pattern Examples12Douglas C. SchmidtDesign Patterns in the Expression Tree Program Factory– Centralize the assembly of resources necessary to create anobject e.g., decouple Node subclass initialization from use Bridge– Decouple an abstraction from its implementation so that the twocan vary independently e.g., printing contents of a subtree and managing memory Adapter– Convert the interface of a class into another interface clients expect e.g., make Tree conform C iostreamsVanderbilt University13

OO Pattern ExamplesDouglas C. SchmidtC Node Interfaceclass Tree; // Forward declaration// Describes the Tree verticesclass Node {friend class Tree;protected: // Only visible to derived classesNode (): use (1) {}/* pure */ virtual void print (std::ostream &) const 0// Important to make destructor virtual!virtual Node ();private:int use ; // Reference counter.};Vanderbilt University14OO Pattern ExamplesDouglas C. SchmidtC Tree Interface#include "Node.h"// Bridge class that describes the Tree edges and// acts as a Factory.class Tree {public:// Factory operationsTree (int);Tree (const string &, Tree &);Tree (const string &, Tree &, Tree &);Tree (const Tree &t);void operator (const Tree &t); Tree ();void print (std::ostream &) const;private:Node *node ; // pointer to a rooted subtreeVanderbilt University15

OO Pattern ExamplesDouglas C. SchmidtC Int Node Interface#include "Node.h"class Int Node : public Node {public:Int Node (int k);virtual void print (std::ostream &stream) const;private:int num ; // operand value.};Vanderbilt University16OO Pattern ExamplesDouglas C. SchmidtC Unary Node Interface#include "Node.h"class Unary Node : public Node {public:Unary Node (const string &op, const Tree &t);virtual void print (std::ostream &stream) const;private:string operation ;Tree operand ;};Vanderbilt University17

toroperatorPARTPARTNodeNodeMemory layouts for different subclasses of NodeUnary atorPARTPARTNodeNodeDoVanderbilt UniversityVanderbilt University Int deptrPARTPARTNodeNodeMemory Layout for C VersionOO Pattern ExamplesOO Pattern ExamplesDouglas C. SchmidtC Binary Node Interface#include "Node.h"class Binary Node : public Node {public:Binary Node (const string &op,const Tree &t1,const Tree &t2);virtual void print (std::ostream &s) const;private:const string operation ;Tree left ;Tree right ;};18

OO Pattern ExamplesDouglas C. SchmidtC Int Node Implementations#include "Int Node.h"Int Node::Int Node (int k): num (k) { }void Int Node::print (std::ostream &stream) const {stream this- num ;}Vanderbilt UniversityOO Pattern Examples20Douglas C. SchmidtC Unary Node Implementations#include "Unary Node.h"Unary Node::Unary Node (const string &op, const Tree &t1): operation (op), operand (t1) { }void Unary Node::print (std::ostream &stream) const {stream "(" this- operation this- operand // recursive call! ")";}Vanderbilt University21

OO Pattern ExamplesDouglas C. SchmidtC Binary Node Implementation#include "Binary Node.h"Binary Node::Binary Node (const string &op,const Tree &t1,const Tree &t2):operation (op), left (t1), right (t2) {}void Binary Node::print (std::ostream &stream) const {stream "(" this- left // recursive call " " this- operation " " this- right // recursive call ")";}Vanderbilt University22OO Pattern ExamplesDouglas C. SchmidtInitializing the Node Subclasses Problem– How to ensure the Node subclasses are initialized properly Forces– There are different types of Node subclasses e.g., take different number & type of arguments– We want to centralize initialization in one place because it is likelyto change . . . Solution– Use a Factory pattern to initialize the Node subclassesVanderbilt University23

OO Pattern ExamplesDouglas C. SchmidtThe Factory Pattern Intent– Centralize the assembly of resources necessary to create anobject Decouple object creation from object use by localizing creationknowledge This pattern resolves the following forces:– Decouple initialization of the Node subclasses from theirsubsequent use– Makes it easier to change or add new Node subclasses later on e.g., Ternary nodes . . . A generalization of the GoF Factory Method patternVanderbilt University24OO Pattern ExamplesDouglas C. SchmidtStructure of the Factory PatternFactorymake product()createsProduct product .return productProductVanderbilt University25

OO Pattern ExamplesDouglas C. SchmidtUsing the Factory Pattern The Factory pattern is used by the Tree class to initialize Nodesubclasses:Tree::Tree (int num): node (new Int Node (num)) {}Tree::Tree (const string &op, const Tree &t): node (new Unary Node (op, t)) {}Tree::Tree (const string &op,const Tree &t1,const Tree &t2): node (new Binary Node (op, t1, t2)) {}Vanderbilt University26OO Pattern ExamplesDouglas C. SchmidtPrinting Subtrees Problem– How do we print subtrees without revealing their types? Forces– The Node subclass should be hidden within the Tree instances– We don’t want to become dependent on the use of Nodes,inheritance, & dynamic binding, etc.– We don’t want to expose dynamic memory management details toapplication developers Solution– Use the Bridge pattern to shield the use of inheritance & dynamicbindingVanderbilt University27

OO Pattern ExamplesDouglas C. SchmidtThe Bridge Pattern Intent– Decouple an abstraction from its implementation so that the twocan vary independently This pattern resolves the following forces that arise when buildingextensible software with C 1. How to provide a stable, uniform interface that is both closed &open, i.e.,– interface is closed to prevent direct code changes– Implementation is open to allow extensibility2. How to manage dynamic memory more transparently & robustly3. How to simplify the implementation of operator Vanderbilt University28OO Pattern ExamplesDouglas C. SchmidtStructure of the Bridge Pattern1: method impl()ImplementorAbstractionmethod impl()method()ConcreteImplementorAmethod impl()ConcreteImplementorBmethod impl()Vanderbilt University29

OO Pattern ExamplesDouglas C. SchmidtUsing the Bridge Pattern1: print()TreeNodeprint()print()Int NodeTernaryprint() BinaryNodeNode Unary print()print()Nodeprint()Vanderbilt UniversityOO Pattern Examples30Douglas C. SchmidtIllustrating the Bridge Pattern in C The Bridge pattern is used for printing expression trees:void Tree::print (std::ostream &os) const {this- node - print (os);} Note how this pattern decouples the Tree interface for printing fromthe Node subclass implementation– i.e., the Tree interface is fixed, whereas the Node implementationvaries– However, clients need not be concerned about the variation . . .Vanderbilt University31

OO Pattern ExamplesDouglas C. SchmidtIntegrating with C I/O Streams Problem– Our Tree interface uses a print method, but most C programmers expect to use I/O Streams Forces– Want to integrate our existing C Tree class into the I/O Streamparadigm without modifying our class or C I/O Solution– Use the Adapter pattern to integrate Tree with I/O StreamsVanderbilt University32OO Pattern ExamplesDouglas C. SchmidtThe Adapter Pattern Intent– Convert the interface of a class into another interface client expects Adapter lets classes work together that couldn’t otherwisebecause of incompatible interfaces This pattern resolves the following force:1. How to transparently integrate the Tree with the C istd::ostreamoperatorsVanderbilt University33

OO Pattern ExamplesDouglas C. SchmidtStructure of the Adapter Pattern1: request ()Targetclientrequest()Adapterrequest()Adaptee2: specific request() specific request()Vanderbilt University34OO Pattern ExamplesDouglas C. SchmidtUsing the Adapter Pattern1: operator Targetclientoperator iostreamTreeoperator print()Vanderbilt University2: print()35

OO Pattern ExamplesDouglas C. SchmidtUsing the Adapter Pattern The Adapter pattern is used to integrate with C I/O Streamsstd::ostream &operator (std::ostream &s, const Tree &trtree.print (s);// This triggers Node * virtual call via// tree.node - print (s), which is// implemented as the following:// (*tree.node - vptr[1]) (tree.node , s);return s;} Note how the C code shown above uses I/O streams to “adapt”the Tree interface . . .Vanderbilt University36OO Pattern ExamplesDouglas C. SchmidtC Tree Implementation Reference counting via the “counted body” idiomTree::Tree (const Tree &t): node (t.node ) {// Sharing, ref-counting. this- node - use ;}void Tree::operator (const Tree &t) {// order important here! t.node - use ;--this- node - use ;if (this- node - use 0)delete this- node ;this- node &t.node ;}Vanderbilt University37

OO Pattern ExamplesDouglas C. SchmidtC Tree Implementation (cont’d)Tree:: Tree () {// Ref-counting, garbage collection--this- node - use ;if (this- node - use 0)delete this- node ;}Vanderbilt University38OO Pattern ExamplesDouglas C. SchmidtC Main Program#include istd::ostream.h #include "Tree.h"int main (int, char *[]) {const Tree t1 Tree ("*", Tree ("-", 5),Tree (" ", 3, 4));cout t1 endl; // prints ((-5) * (3 4))const Tree t2 Tree ("*", t1, t1);// prints (((-5) * (3 4)) * ((-5) * (3 4))).cout t2 endl;return 0;// Destructors of t1 \& t2 recursively} // delete entire tree when leaving scope.Vanderbilt University39

OO Pattern ExamplesDoOO Pattern ExamplesExpression Tree Diagram 2Expression Tree Diagram 1t1t2**BinaryNodet1* IntNode3UnaryNode443 Expression tree for t1 ((-5) * (3 4))Expression tree for t2 (t1 * t1)Vanderbilt UniversityBinaryNode 5 print()-UnaryNodeprint()-5DoVanderbilt UniversityIntNode

OO Pattern ExamplesDouglas C. SchmidtAdding Ternary Nodes Extending the existing program to support ternary nodes isstraightforward– i.e., just derive new class Ternary Node to handle ternaryoperators, e.g., a b ? c : d, etc.#include "Node.h"class Ternary Node : public Node {public:Ternary Node (const string &, const Tree &,const Tree &, const Tree &);virtual void print (std::ostream &) const;private:const string operation ;Tree left , middle , right ; };Vanderbilt UniversityOO Pattern Examples42Douglas C. SchmidtC Ternary Node Implementation#include "Ternary Node.h"Ternary Node::Ternary Node (const string &op,const Tree &a,const Tree &b,const Tree &c): operation (op), left (a), middle (b),right (c) {}void Ternary Node::print (std::ostream &stream) const {stream this- operation "(" this- left // recursive call "," this- middle // recursive call "," this- right // recursive call ")";}Vanderbilt University43

OO Pattern ExamplesDouglas C. SchmidtC Ternary Node Implementation (cont’d)// Modified class Tree Factoryclass Tree {// add 1 class constructorpublic:Tree (const string &, const Tree &,const Tree &, const Tree &): node (new Ternary Node (op, l, m, r)) {}// Same as before . . .Vanderbilt UniversityOO Pattern Examples44Douglas C. SchmidtDifferences from Algorithmic Implementation On the other hand, modifying the original algorithmic approachrequires changing (1) the original data structures, e.g.,struct Tree Node {enum {NUM, UNARY, BINARY, TERNARY} tag ; // same as beforeunion {// same as before. But, add this:struct {Tree Node *l , *m , *r ;} ternary ;} c;#define ternary c.ternary};Vanderbilt University45

OO Pattern ExamplesDouglas C. SchmidtDifferences from Algorithmic Implementation (cont’d) & (2) many parts of the code, e.g.,void print tree (Tree Node *root) {// same as beforecase TERNARY: // must be TERNARY.printf ("(");print tree (root- ternary .l );printf ("%c", root- op [0]);print tree (root- ternary .m );printf ("%c", root- op [1]);print tree (root- ternary .r );printf (")"); break;// same as before}Vanderbilt UniversityOO Pattern Examples46Douglas C. SchmidtSummary of Expression Tree Example OO version represents a more complete modeling of the applicationdomain– e.g., splits data structures into modules that correspond to“objects” & relations in expression trees Use of C language features simplifies the design and facilitatesextensibility– e.g., implementation follows directly from design Use of patterns helps to motivate, justify, & generalize design choicesVanderbilt University47

OO Pattern ExamplesDouglas C. SchmidtPotential Problems with OO Design Solution is very “data structure rich”– e.g., requires configuration management to handle many headers& .cpp files! May be somewhat less efficient than original algorithmic approach– e.g., due to virtual function overhead In general, however, virtual functions may be no less inefficient thanlarge switch statements or if/else chains . . . As a rule, be careful of micro vs. macro optimizations– i.e., always profile your code!Vanderbilt University48OO Pattern ExamplesDouglas C. SchmidtCase Study: System Sort Develop a general-purpose system sort– It sorts lines of text from standard input and writes the result tostandard output– e.g., the UNIX system sort In the following, we’ll examine the primary forces that shape thedesign of this application For each force, we’ll examine patterns that resolve itVanderbilt University49

OO Pattern ExamplesDouglas C. SchmidtExternal Behavior of System Sort A “line” is a sequence of characters terminated by a newline Default ordering is lexicographic by bytes in machine collatingsequence (e.g., ASCII) The ordering is affected globally by the following options:––––– Ignore case (-f)Sort numerically (-n)Sort in reverse (-r)Begin sorting at a specified field (-k)Begin sorting at a specified column (-c)Your program need not sort files larger than main memoryVanderbilt University50OO Pattern ExamplesDouglas C. SchmidtHigh-level Forces Solution should be both time & space efficient– e.g., must use appropriate algorithms and data structures– Efficient I/O & memory management are particularly important– Our solution uses minimal dynamic binding (to avoid unnecessaryoverhead) Solution should leverage reusable components– e.g., istd::ostreams, Array & Stack classes, etc. Solution should yield reusable components– e.g., efficient input classes, generic sort routines, etc.Vanderbilt University51

OO Pattern ExamplesDouglas C. SchmidtTop-level Algorithmic View of the Solution Note the use of existing C mechanisms like I/O streams// Reusable function:// template typename ARRAY void sort (ARRAY &a);int main (int argc, char *argv[]){parse args (argc, argv);Input input;cin input;sort (input);cout input;}Vanderbilt UniversityOO Pattern Examples52Douglas C. SchmidtTop-level Algorithmic View of the Solution (cont’d) Avoid the grand mistake of using top-level algorithmic view tostructure the design . . .– Structure the design to resolve the forces!– Don’t focus on algorithms or data, but instead look at the problem,its participants, & their interactions!Vanderbilt University53

OO Pattern ExamplesDouglas C. SchmidtGeneral OOD Solution Approach Identify the classes in the application/problem space & solution space– e.g., stack, array, input class, options, access table, sorts, etc. Recognize & apply common design patterns– e.g., Singleton, Factory, Adapter, Iterator Implement a framework to coordinate components– e.g., use C classes & parameterized typesVanderbilt University54OO Pattern ExamplesDouglas C. SchmidtC Class ModelSystemSortOptionsGLOBALSort ATAdapterSortSTRATEGICCOMPONENTSLine PtrsSort STYPEStackVanderbilt UniversityInputTYPEArray55

OO Pattern ExamplesDouglas C. SchmidtC Class Components Tactical components– Stack Used by non-recursive quick sort– Array Stores/sorts pointers to lines & fields– Access Table Used to store input– Input Efficiently reads arbitrary sized input using only 1 dynamicallocation & 1 copyVanderbilt University56OO Pattern ExamplesDouglas C. SchmidtC Class Components Strategic components– System Sort Facade that integrates everything . . .– Sort AT Adapter Integrates Array & Access Table– Options Manages globally visible options– Sort e.g., both quicksort & insertion sortVanderbilt University57

OO Pattern ExamplesDouglas C. SchmidtDetailed Format for Solution Note the separation of concerns// Prototypestemplate typename ARRAY void sort (ARRAY &a);void operator (std::istream &, Sort AT Adapter &);void operator (std::ostream &, const Sort AT Adapter &int main (int argc, char *argv[]){Options::instance ()- parse args (argc, argv);cin System Sort::instance ()- access table ();sort (System Sort::instance ()- access table ());cout System Sort::instance ()- access table ();}Vanderbilt University58OO Pattern ExamplesDouglas C. SchmidtReading Input Efficiently Problem– The input to the system sort can be arbitrarily large (e.g., up to 1/2size of main memory) Forces– To improve performance solution must minimize:1. Data copying & data manipulation2. Dynamic memory allocation Solution– Create an Input class that reads arbitrary input efficientlyVanderbilt University59

OO Pattern ExamplesDouglas C. SchmidtAccess Table FormatACCESS ARRAYACCESS BUFFERVanderbilt University60OO Pattern ExamplesDouglas C. SchmidtThe Input Class Efficiently reads arbitrary-sized input using only 1 dynamic allocationclass Input {public:// Reads from input up to terminator , replacing search // with replace .Returns dynamically allocated buffer.char *read (std::istream &input, int terminator EOF,int search ’\n’, int replace ’\0’);// Number of bytes replaced.size t replaced () const;// Size of buffer.size t size () const;private:// Recursive helper method.char *recursive read ();// . . .};Vanderbilt University61

OO Pattern ExamplesDouglas C. SchmidtThe Input Class (cont’d)char *Input::read (std::istream &i, int t, int s, int r){// Initialize all the data members.return recursive read ();}char *Input::recursive read () {char buffer[BUFSIZ];// 1. Read input one character at a time, performing//search/replace until EOF is reached or buffer//is full.// 1.a If buffer is full, invoke recursive read()//recursively.// 1.b If EOF is reached, dynamically allocate chunk//large enough to hold entire input// 2. On way out of recursion, copy buffer into chunk}Vanderbilt UniversityOO Pattern Examples62Douglas C. SchmidtDesign Patterns in the System Sort Facade– Provide a unified interface to a set of interfaces in a subsystem Facadedefines a higher-level interface that makes thesubsystem easier to use– e.g., sort() function provides a facade for the complex internaldetails of efficient sorting Adapter– Convert the interface of a class into another interface clients expect Adapter lets classes work together that couldn’t otherwisebecause of incompatible interfaces– e.g., make Access Table conform to interfaces expected bysort & istd::ostreamsVanderbilt University63

OO Pattern ExamplesDouglas C. SchmidtDesign Patterns in System Sort (cont’d) Factory– Centralize assembly of resources needed to create objects– e.g., decouple initialization of Line Ptrs used by Access Tablefrom their subsequent use Bridge– Decouple an abstraction from its implementation so that the twocan vary independently– e.g., comparing two lines to determine ordering Strategy– Define a family of algorithms, encapsulate each one, & make theminterchangeable– e.g., allow flexible pivot selectionVanderbilt UniversityOO Pattern Examples64Douglas C. SchmidtDesign Patterns in System Sort (cont’d) Singleton– Ensure a class has only one instance, & provide a global point ofaccess to it– e.g., provides a single point of access for the system sort facade &for program options Iterator– Provide a way to access the elements of an aggregate objectsequentially without exposing its underlying representation– e.g., provides a way to print out the sorted lines without exposingrepresentation or initializationVanderbilt University65

OO Pattern ExamplesDouglas C. SchmidtSort Algorithm For efficiency, two types of sorting algorithms are used:1. Quicksort– Highly time & space efficient sorting arbitrary data– O(n log n) average-case time complexity– O(n2) worst-case time complexity– O(log n) space complexity– Optimizations are used to avoid worst-case behavior2. Insertion sort– Highly time & space efficient for sorting “almost ordered” data– O(n2) average- & worst-case time complexity– O(1) space complexityVanderbilt University66OO Pattern ExamplesDouglas C. SchmidtQuicksort Optimizations1. Non-recursive Uses an explicit stack to reduce function call overhead2. Median of 3 pivot selection Reduces probability of worse-case time complexity3. Guaranteed (log n) space complexity Always “pushes” larger partition4. Insertion sort for small partitions Insertion sort runs fast on almost sorted dataVanderbilt University67

OO Pattern ExamplesDouglas C. SchmidtSelecting a Pivot Value Problem– There are various algorithms for selecting a pivot value e.g., randomization, median of three, etc. Forces– Different input may sort more efficiently using different pivotselection algorithms Solution– Use the Strategy pattern to select the pivot selection algorithmVanderbilt University68OO Pattern ExamplesDouglas C. SchmidtThe Strategy Pattern Intent– Define a family of algorithms, encapsulate each one, & make theminterchangeable Strategy lets the algorithm vary independently from clients thatuse it This pattern resolves the following forces1. How to extend the policies for selecting a pivot value withoutmodifying the main quicksort algorithm2. Provide a one size fits all interface without forcing a one size fits allimplementationVanderbilt University69

OO Pattern ExamplesDouglas C. SchmidtStructure of the Strategy PatternSTRATEGYContextStrategyalgorithm interface()context interface()ConcreteStrategy AConcreteStrategy Calgorithm interface()algorithm interface()ConcreteStrategy Balgorithm interface()Vanderbilt University70OO Pattern ExamplesDouglas C. SchmidtUsing the Strategy PatternPi votStrategyquick sortget pivot()pivot strat- get pivot (array, lo, hi)SelectFirstVanderbilt UniversityRandomMedianofThree71

OO Pattern ExamplesDouglas C. SchmidtImplementing the Strategy Pattern ARRAY is the particular “context”template typename ARRAY void sort (ARRAY &array) {Pivot Strategy ARRAY *pivot strat Pivot Factory ARRAY ::make pivot(Options::instance ()- pivot strat ());std::auto ptr Pivot Strategy ARRAY holder (pivot strat);// Ensure exception safety.ARRAY temp array;quick sort (temp, pivot strat);// Destructor of holder deletes pivot strat .array temp;}Vanderbilt University72OO Pattern ExamplesDouglas C. SchmidtImplementing the Strategy Patterntemplate typename ARRAY, class PIVOT STRAT quick sort (ARRAY &array,PIVOT STRAT *pivot strat) {for (;;) {typename ARRAY::TYPE pivot // Note ’lo’ & ’hi’ should be passed by reference// so get pivot() can reorder the values & update// ’lo’ & ’hi’ accordingly.pivot strat- get pivot (array, lo, hi);// Partition array[lo, hi] relative to pivot . . .}}Vanderbilt University73

OO Pattern ExamplesDouglas C. SchmidtFixed-size Stack Defines a fixed size stack for use with non-recursive quicksorttemplate typename T, size t SIZE class Fixed Stack{public:bool push (const T &new item);bool pop (T &item);bool is empty ();// . . .private:T stack [SIZE];size t top ;};Vanderbilt University74OO Pattern ExamplesDouglas C. SchmidtDevising a Simple Sort Interface Problem– Although the implementation of the sort function is complex, theinterface should be simple to use Key forces– Complex interface are hard to use, error prone, and discourageextensibility & reuse– Conceptually, sorting only makes a few assumptions about the“array” it sorts e.g., supports operator[] methods, size, & trait TYPE– We don’t want to arbitrarily limit types of arrays we can sort Solution– Use the Facade & Adapter patterns to simplify the sort programVanderbilt University75

OO Pattern ExamplesDouglas C. SchmidtFacade Pattern Intent– Provide a unified interface to a set of interfaces in a subsystem Facadedefines a higher-level interface that makes thesubsystem easier to use This pattern resolves the following forces:1. Simplifies the sort interface– e.g., only need to support operator[] & size methods, &element TYPE2. Allows the implementation to be efficient and arbitrarily complexwithout affecting clientsVanderbilt University76OO Pattern ExamplesDouglas C. SchmidtStructure of the Facade PatternEXTERNALLYVISIBLEFacadeHIDDENVanderbilt University77

OO Pattern ExamplesDouglas C. SchmidtUsing the Facade PatternEXTERNALLY

OO Pattern Examples Douglas C. Schmidt Relationships Between Tree & Node Classes Unary Node Node Tree 3 1 1 1 1 2 Binary Node Ternary Node Int Node has-a Vanderbilt University 12 OO Pattern Examples Douglas C. Schmidt Design Patterns in the Expression Tree Program Factory – Centralize the

Related Documents:

method dispatch in different object-oriented programming languages. We also include an appendix on object-oriented programming languages, in which we consider the distinction between object-based and object-oriented programming languages and the evolution and notation and process of object-oriented analysis and design, start with Chapters 5 and 6;

Object Class: Independent Protection Layer Object: Safety Instrumented Function SIF-101 Compressor S/D Object: SIF-129 Tower feed S/D Event Data Diagnostics Bypasses Failures Incidences Activations Object Oriented - Functional Safety Object: PSV-134 Tower Object: LT-101 Object Class: Device Object: XS-145 Object: XV-137 Object: PSV-134 Object .

as object–oriented design. Object–oriented development approaches are best suited to projects that will imply systems using emerging object technologies to construct, manage, and assemble those objects into useful computer applications. Object oriented design is the continuation of object-oriented analysis,

Object oriented design methods emerged in the 1980s, and object oriented analysis methods emerged during the 1990s. In the early stage, object orientation was largely . and extensible system. Whole object oriented modeling is covered by using three kinds of models for a system description. These models are: object model,

object-oriented programming language is based on a kind of old object-oriented programming language. For example, though C language is an object-oriented programming language, it still retains the pointer which is complex but has strong function. But C# improved this problem. C# is a kind of pure object-oriented language.

Reusability, CK Metric, Object - Oriented. 1. INTRODUCTION Object oriented systems continue to share a major portion of software development and customer base for these systems is on the rise. This is because there are many advantages in taking the object oriented concept. The weakness though is that most object oriented systems tend to be .

Object built-in type, 9 Object constructor, 32 Object.create() method, 70 Object.defineProperties() method, 43–44 Object.defineProperty() method, 39–41, 52 Object.freeze() method, 47, 61 Object.getOwnPropertyDescriptor() method, 44 Object.getPrototypeOf() method, 55 Object.isExtensible() method, 45, 46 Object.isFrozen() method, 47 Object.isSealed() method, 46

2 Database System Concepts 8.3 Silberschatz, Korth and Sudarshan Object-Oriented Data Model! Loosely speaking, an object corresponds to an entity in the E- R model.! The object-oriented paradigm is based on encapsulating code and data related to an object into single unit.! The object-oriented data model is a logical data model (like