, 1 3 Schmidt Schmidt C. C. patterns Strategy & Douglas Douglas C++ Metho d, Singleton r, ry 4 4 using NODES acto BINARY F Iterato atterns + P studies Diagram

acade, 3 3 F case NODES Singleton, INTEGER ree Using r, T re

a * w several Bridge Metho d, 5 5 Iterato , soft ry ry Studies ression acto _ _ _ _ acto describ e F F Exp , Adapter, Case extensible ree include slides NODE T UNARY rt y y acade, So Strategy Adapter, F eri er wing highly , , , V ression Examples Examples rt Universit Universit follo examples e.g. e.g. e.g. Bridge build Exp System So { { { attern attern P P The to The 1. 2. 3. anderbilt anderbilt   OO V V OO , 2 ry una Schmidt C. y constructs with op erands r Douglas EECS asso ciativities whereas & of rs Universit . example . 343-8197 di erent . Studies rtment Evaluato op erato , etc. rguments, a anderbilt addition o binding Depa 615 V ree levels w T t Case example C++ riables, over Schmidt va has containing this & r C. dynamic in one recedence schmidt/ ression p no des  & recedence doubles, Design , p of op erato only Exp es integers e.g. atterns has , Douglas tak di erent r P consist integers, rities handle inheritance Study: a re have a trees op erato r rs just multiplication y trees wing Case e'll di erent Multiplication The W minus ression Examples follo    Universit Op erato & Op erands Professo www.dre.vanderbilt.edu/ [email protected] ression Exp   Object-Oriented attern P { The exp anderbilt  V OO y Universit anderbilt V y Universit anderbilt V

}

};

}

c.binary_ binary_ define

type\n"; unknown "error, printf

c.unary_ unary_ define

default:

c; }

break; ""; printf

binary_; } *r_; *l_, Tree_Node { struct

ro-bnr_r; root->binary_.r_ print_tree

*unary_; Tree_Node

root->op_[0]; "s", printf

{ union

ro-bnr_l; root->binary_.l_ print_tree

o.op_ op_ define

""; printf

o.num_ num_ define

BINARY: case

o; }

break; ""; printf

num_; int

root->unary_; print_tree

op_[2]; char

root->op_[0]; "s", printf

{ union

UNARY: case

*/ count reference /* use_; short

break;

tag_; } BINARY UNARY, NUM, { enum

root->num_; "d", printf NUM: case

{ Tree_Node struct

{ root->tag_ switch

Tree_Node; Tree_Node struct typedef

{ *root Tree_Node print_tree void

, e.g. structure, data resent rep

, e.g. tree, a

to struct/union a using involves trees ression exp

evaluate & build to function recursive a & statement

implementing r fo d metho rithmic algo ypical t A 

switch a use implementation rithmic algo ypical t A 

ersion V rithmic Algo unction F ree T Print

o D Examples attern P OO o D Examples attern P OO 4 6 Schmidt Schmidt C. C. , Douglas Douglas e.g. ersion V r object rder op erations, Node tree traversals level-o rithmic Behavio rious Tree tree va rder, ree ression Algo rm di erent T re-o exp struct of p via ression Tree a Node p erfo the of y exp out rder, of y ma analysis ression 1|2 out the 1 CLASS y La la p ost-o step Exp RELATIONSHIPS rint ry ry \evaluated" Tree p Node \value" co de & be rder, semantic the y trees memo y y rm in-o Memo ma , evaluation the erfo raverse Examples Examples Universit Universit e.g. T Return Generate P rees ression T The      op_ tag_ use_ num_ attern attern unary_ binary_ P P { { Here's Exp LAYOUT MEMORY anderbilt anderbilt   OO V OO V 9 11 & Schmidt Schmidt C. C. the structs of , Douglas Douglas & wrt roach size e.g. . the App design . 4 4 . NODES BINARY extend, bigger entire assumptions tags to + w the rithmic the yp e Diagram t rse b elo 3 3 o o ccurs rst-case on dicult NODES w Algo o INTEGER ree it w T through

es * ypically with t extension 5 5 mak b ecomes switching ripple making but ry" y es ression b will _ _ _ _ roblem Exp \terna p mistak space b ecomes! e rganization NODE essential, o the UNARY changes Limitations this y y mak astes not item see re w , that to is small rogram Examples Examples Mo Universit Universit p e.g. rgest Any Easy This implementation la Note  attern attern P P { { { { The Solution unions anderbilt anderbilt   V OO V OO , 8 10 of rk 30 o i.e. - w !a Schmidt Schmidt riented yp es 10 C. C. domain, t no de in include b, edges, +10, ree + T rious Douglas Douglas vertices: a ro cessing object-o va -10, p to , roach structures domain results , resentation tree roach an int application e.g. app een e.g. rep w data most rs, ression-tree which rs, App bet do tree" the with ression exp union rithmic application exp in op erato converting than select op erato algo domain, the ression ry roach to ry rithmic rcs in functions a edges describ es bina app \exp rather una ypical & & & t used describ es implicitly Algo the that Alternative r re roblem: rch! the entities a trees p application fo of that rithms picture no des involved: handles sea handles rithmic with OO co de vertices the with ry \passive" algo used No des een same class mo del of algo encapsulation ression w in re riginal No de: bina a classes No de: o een the of edges bet mo deling exp base statements \glue" w r ry to ry No de: & fo classes use b eing with bet the OO limitations y Bina Una Int revious ree: several mo deling re no in r p y y back T No de: o switch r Limitations no des coupling these o structures with , , go class class class , Examples Examples rt    Universit Universit no des Compa e.g. class class i.e. relations explicitly Data Little Complexit Tight e.g. Discover Sta Note,    { { attern attern P P { { { { Contrast Incomplete Problems decomp osition 3. 2. 1. anderbilt anderbilt    OO V V OO 13 15 can o Schmidt Schmidt w C. C. t exp ect object ry the an Douglas Douglas clients that Program memo and so create use ree to T interface edges from ry subtree managing &; Tree and necessa another ression Tree iostreams Interface implementation the rooted const; into initialization Exp &; &, &t; a its subtree ree & C++ a to resources T class the from of Tree Tree Tree a rm of sub class in of describes &, &, confo C++ &t; pointer Node const contents assembly that // Tree abstraction interface string string Tree atterns e Factory. operations std::ostream the P an the a { rinting y y p mak decouple class "Node.h" , , , indep endently as ; int; const const const operator= print *node_; Examples Examples ry Universit Universit ry e.g. e.g. e.g. Tree Factory Design Decouple va Centralize Convert    acto attern attern Bridge acts P P { { { Bridge F Adapter // Tree Tree Tree Tree void ~Tree void Node anderbilt anderbilt    OO V OO include // V // class public: private: 12 14 0; Schmidt Schmidt = C. C. const Douglas Douglas & Classes Int

Node Node No de classes

& has-a virtual! ree std::ostream Interface T derived 1 1 Node Unary to een Tree print No de counter. w declaration destructor 2 vertices Bet 3 void {} visible C++ make Tree 1 1 ; 1 Forward to Reference Only Node Binary virtual Tree; the Node // // Ternary { // use_ y y */ ~Node class : Examples Examples Relationships Universit Universit Tree; Node use_; pure Important attern attern Describes P P /* Node // virtual int anderbilt anderbilt OO class }; // class friend protected: private: OO V V y Universit anderbilt V 17 Schmidt C. Douglas

Node of classes sub di erent r fo outs y la ry Memo  const;

&t;

Node

Ternary

Int_Node

) PART

Tree (Tree ) PART (Tree (Tree

right

right_

num num_

Interface Node &stream

Binary

PART const PART

{ Node Node

(Tree (Tree ) PART

) PART (Tree (Tree

) PART (Tree (Tree

) PART

No de (Tree middle

middle_ right right_ &op,

Node

ry Node Unary

Node

use use_

Una

) PART ) PART ) PART

(Tree (Tree (Tree (Tree

) PART ) PART ) PART (Tree (Tree (Tree std::ostream (Tree

left left operand

vptr left_ left_ operand_ string vptr public

:

op op

C++

print

operator operator operator

operator_ operator_ operator_ Tree

const tag tag

ptr

y node_

PART PART void PART "Node.h" PART PART PART

operation_; Node Node Node Node Node Node operand_; Examples Universit Unary_Node

ersion V C++ r fo out y La ry Memo attern P Unary_Node virtual string Tree

o D Examples attern P OO include anderbilt public: private: }; OO V class 16 18 Schmidt Schmidt C. C. Douglas Douglas const; const; Interface &stream &s Interface { No de { &op, No de Node &t1, &t2; ry Node Int value. Bina std::ostream string Tree Tree std::ostream public : public C++ k; : print operand const print const operation_; C++ const // int y y void "Node.h" "Node.h" void string left_; right_; Examples Examples Universit Universit Int_Node Binary_Node num_; attern attern P P Int_Node virtual int Binary_Node virtual const Tree Tree include include anderbilt anderbilt OO public: class OO V V class private: public: }; private: }; 21 23 to ely Schmidt Schmidt C. C. lik &t1 { is it Douglas Douglas Tree const rop erly p b ecause const call! sub classes place rguments } &stream &op, a initialized << Sub classes { No de one of re a in the sub classes Implementations yp e recursive t1 string t No de & // No de the No de initialize of sub classes std::ostream const initialization to ry numb er operand_ yp es t No de this->operation_ Una the << pattern op, centralize di erent ry Initializing . di erent e to this->operand_ ""; "" . C++ y y ensure . re acto tak "Unary_Node.h" a F << << << , ant to a w Examples Examples w Universit Universit e e.g. Unary_Node::print change Use W Ho There rces  operation_ o attern attern P P { { { { Solution Problem F stream : include anderbilt anderbilt    OO Unary_Node::Unary _N ode V OO V } void 20 22 Schmidt Schmidt C. C. { { Douglas Douglas const call const call {} } &op, t2 &stream { &t1, &t2: &stream recursive recursive k string Tree Tree // Implementation right_ // Implementations num_ const const No de const t1, k: std::ostream No de ry std::ostream Int int left_ this->left_ this->operation_ this->right_ Bina << << << " " op, C++ this->num_; "" " " ""; C++ y y "Int_Node.h" "Binary_Node.h" << << << << << Examples Examples Universit Universit Int_Node::print Binary_Node::prin t attern attern P P stream operation_ stream include include anderbilt anderbilt OO Int_Node::Int_Nod e OO void V V Binary_Node::Bina ry _No de } void } 25 27 to Schmidt Schmidt C. C. dynamic details & inheritance, , Douglas Douglas instances Nodes yp es? t Tree of inheritance management attern their the use P of ry the ry use within on memo the revealing acto F Subtrees hidden Product product = ... return product Product product = ... return product shield dynamic the be without dep endent to of Printing etc. exp ose should Factory Factory Product become Product make_product() subtrees to pattern to creates creates rint ant p binding, develop ers ant w Structure sub class e w Bridge w y y do the Node don't don't Examples Examples w dynamic Universit Universit e e & application Use binding W The W Ho rces o attern attern P P { { { { { Solution F Problem anderbilt anderbilt    OO V OO V 24 26 Schmidt Schmidt C. C. creation on object sub classes: subsequent an Douglas Douglas later their No de lo calizing create y from b to &t {} ry sub classes initialize use pattern to attern Tree t2 P {} No de attern necessa class sub classes ry P object t1, rces: Metho d {} t new ree fo const ry ry T Node acto from add F op, the r acto wing op, resources acto o the y F &op, &op, . b F num of . &t1, &t2 the of follo . GoF creation used the The change is string string Tree Tree the num to no des Using assembly of Int_Node Unary_Node Binary_Node ry object the resolves initialization pattern int const const easier erna const const y y ry T new new new it , wledge es Examples Examples acto pattern Universit Universit Decouple e.g. kno F Centralize use Mak Decouple generalization   node_ node_ node_ attern attern P P { { { Intent A The This : : : Tree::Tree anderbilt anderbilt     OO OO V V Tree::Tree Tree::Tree 29 31 the Schmidt Schmidt . . C. C. from . Douglas Douglas implementation rinting riation p { r va C++ fo Node trees: in the attern Concrete Concrete const the method_impl() P ImplementorB ImplementorB method_impl() ab out ression interface Implementor Implementor attern &os exp P whereas Tree Bridge , the rinting concerned p the xed Concrete Concrete r Bridge be method_impl() is fo of os; ImplementorA ImplementorA not the 1: method_impl() std::ostream decouples used is need interface implementation pattern Structure clients pattern Tree method() y y this Illustrating Abstraction Abstraction w Tree::print the ever, Examples Examples sub class ho , w Universit Universit Bridge ries va Ho i.e. this->node_->pri nt void attern attern P P { { } Note The Node anderbilt anderbilt   OO V OO V , 28 30 can op en o Schmidt Schmidt w C. C. t building & the robustly Douglas Douglas when closed & that rise so b oth a rently is y Node Node print() that changes Ternary Ternary that attern transpa print() operator<< Node P rces co de re attern of fo Node print() Node extensibilit P Unary Unary mo implementation interface w ry direct its wing rm allo Bridge Node Node to Binary Binary print() follo memo Bridge from unifo revent the p 1: print() C++ the op en to implementation The print() is Int Node Int Node stable, with dynamic the a Using re closed abstraction a resolves w is print() Tree Tree an rovide y y manage simplify p soft to to to indep endently pattern Examples Examples , w w w Universit Universit ry Implementation interface Ho Ho i.e. Ho va Decouple { { attern attern P P { extensible This Intent 2. 3. 1. anderbilt anderbilt   OO OO V V 33 35 Schmidt Schmidt C. C. b ecause exp ects istd::ostream Douglas Douglas client otherwise C++ print() Tree Tree the interface couldn't attern with Target Target P operator<< attern that another P Tree rce: fo into the together Adapter 2: print() wing class rk a Adapter o follo the w 1: operator<< integrate of the interfaces The rently classes Using interface lets resolves the y y client client transpa rs operator<< iostream iostream to incompatible Examples Examples w pattern Universit Universit Adapter of op erato Ho Convert  attern attern P P { This Intent 1. anderbilt anderbilt   OO V OO V 32 34 Schmidt Schmidt Stream C. C. I/O rogrammers p Douglas Douglas the Streams C++ into I/O I/O Adaptee attern Adaptee most Streams specific_request() P class with but C++ r I/O request() o Target Target Tree Tree class metho d, Adapter C++ C++ our integrate the print to with a of existing 1: request () 2: specific_request() uses our Streams mo difying pattern I/O Structure use interface without integrate Integrating Adapter y y to to the Tree request() client client Adapter Adapter Examples Examples radigm Universit Universit ant Our exp ect W Use pa rces o attern attern P P { { { Problem F Solution anderbilt anderbilt    OO OO V V 37 39 Schmidt Schmidt C. C. Douglas Douglas 4 4. { + + 3 3 5, * * ref-counting. 4; idiom { scope. t.node_ 3, "-", &t -5 -5 t1; body" Program * node_ Sharing, Tree "+", t1, recursively leaving Tree Implementation 0 4 // prints t2 Main { + \counted &t: == Tree when ree "*", // "*", \& T 3 const the here! *[] t1 * C++ Tree tree via return; Tree Tree of t.node_; = endl; = endl; C++ char &t = t1 << t2 << -5 const entire == this->node_; y y counting important t1 t2 int, "Tree.h" 0; Tree Tree << << Examples Examples Universit Universit Tree::operator= this this->node_->use _ Destructors delete prints order delete main attern attern ++this->node_->u se_ ; P P Reference if ++t.node_->use_; --this->node_->us e_; if this->node_ const cout const cout return // // // Tree::Tree // anderbilt anderbilt  OO V OO V } void } include include int } { 36 38 the &tree Schmidt Schmidt C. C. Tree \adapt" Douglas Douglas to Streams const I/O s; via &s, streams cont'd C++ I/O attern call is P with uses which tree.node_, ab ove virtual integrate std::ostream collection Adapter * following: 0 wn to s, Implementation sho the the Node used is as garbage ree co de T . { Using . s; &operator<< . C++ pattern  triggers s; C++ this->node_; y y the w This tree.node_->print implemented *tree.node_->vptr [1]  Examples Examples interface ho Universit Universit Adapter Ref-counting, this->node_->use _< = tree.print // // return // // delete attern attern P P Tree } Note The std::ostream // --this->node_->us e_; if Tree::~Tree anderbilt anderbilt   OO OO V V } y Universit anderbilt V 43 Schmidt { C.

t1 * t1 = t2 r fo tree ression Exp  Douglas const

call

call

3

3 &op, 5

5 b,

4 4 &a, &b, &c &stream call recursive recursive string Tree Tree Tree

//

Implementation

middle_ "" // Node

Int

+ << - const const const const a, recursive No de std::ostream

//

ry Node

print() * Unary left_

this->middle_ this->right_ erna t1 T

<< <<

op, {}

Node

* Binary this->operation_ this->left_ "," "," ""; c y C++

"Ternary_Node.h" << << << << << t2 Examples Universit Ternary_Node::pri nt

2 Diagram ree T ression Exp operation_ right_ attern P : stream

o D Examples attern P OO anderbilt OO include Ternary_Node::Ter na ry_ No de V void }

y Universit anderbilt V is 42 rs, Schmidt C. no des op erato ry Douglas ry terna terna

4 + 3 * -5 = t1 r fo tree ression Exp  &, rt handle

Tree const;

to

Node supp o

3

3 No des & 5 5 Int

4 4 to { No de ry const &; }; ry &, Node erna

erna Node T Tree

rogram T

p Unary

right_;

+ string etc. - public std::ostream class const d, : : Adding

new &, c existing Node

? const print operation_;

Binary middle_,

b

print() rd * the Tree a derive y void == rw

"Node.h"

a t1 string just , left_, Examples , Universit Ternary_Node const e.g. i.e.

1 Diagram ree T ression Exp attern P { Extending straightfo Ternary_Node virtual const Tree

o D Examples attern P OO anderbilt  public: class include OO V private: 45 47 Schmidt Schmidt requires C. C. \objects" facilitates choices application to Douglas Douglas roach and the design app of rresp ond design Example co rithmic , the design generalize Implementation ree that mo deling algo & e.g. T , from this: riginal justify simpli es o mo dules add rithmic complete ression directly structures, the re *r_; into ws trees Algo TERNARY But, mo Exp data features motivate, a follo before *m_, of to from ression mo difying as { ry structures riginal c.ternary_ o BINARY, *l_, exp resents helps before. language in hand, data the same rep as { y y y Summa 1 // C++ UNARY, other splits implementation Tree_Node ternary_ { patterns , , same { Examples Examples relations of Di erences version Universit Universit ternary_; Tree_Node of the e.g. & e.g. } c; tag_; // struct NUM, attern attern P P { { changing extensibilit Use Use domain On OO } } union enum struct anderbilt anderbilt     define }; OO V OO V 44 46 Schmidt Schmidt C. C. cont'd Douglas Douglas cont'd {} r m, &, { l, Implementation Tree , & op, Implementation e.g. *root TERNARY. rithmic const Tree be Factory co de, . No de &, . Algo the must ry Tree const root->op_[0]; root->op_[1]; break; . of Tree_Node // constructor &, Ternary_Node root->ternary_.l _ ; root->ternary_.m _ ; root->ternary_.r _ ; rts string from erna before before T pa class { ""; "c", "c", ""; before y y Tree as new as class as many 1 const TERNARY: Examples Examples Universit Universit C++ Tree print_tree same same 2 const node_ printf print_tree printf print_tree printf print_tree printf attern attern Modified add Same P P & Tree // case : // Di erences anderbilt anderbilt  OO // class // public: OO V V void // } 49 51 ry to Schmidt Schmidt design C. C. result the rtant unnecessa the Douglas Douglas imp o shap e avoid rly etc. writes it that structures to rt and rticula etc. So rces data pa fo resolve routines, re ry binding a rces input and rt o ecient that so classes, F rd rt rima p System so comp onents rithms space Stack the dynamic standa comp onents generic & patterns algo & rt management system y so Study: from reusable time ry riate High-level Arra examine minimal classes, reusable rop examine text both e'll memo Case system app e'll w of uses leverage yield input be & w use output UNIX I/O rce, lines wing, y y general-purp ose fo rd should should should a solution istd::ostreams, ecient the must rts application follo , , , , Examples Examples so Universit Universit each the this e.g. Our overhead e.g. It standa e.g. Ecient e.g. r o attern attern P P { { { { { { { of F Solution Solution In Solution Develop anderbilt anderbilt       OO V OO V 48 50 & rge la Schmidt Schmidt C. C. sequence than headers roach Douglas Douglas app ry many rt collating newline inecient a So memo options: Design y rithmic b less handle algo no main to machine wing OO  in be optimizations System y follo -c than  .  riginal ytes o with . ma of terminated -k b the  . r rger y y macro la b b rich" than management overhead eld column vs. racters les chains functions co de! rt cha globally Behavio so Problems micro ecient  of structure our function if/else sp eci ed sp eci ed  y of -n virtual not r  a a lexicographic less o -r   is con guration at at \data a ected reful -f ro le ever, virtual need  p is ca w sequence otential External to ys a very rting rting ho P y y be a reverse case rdering is so so is les! somewhat o requires due in numerically statements alw re rogram , , ASCI I rdering Examples Examples , p rule, be rt rt Universit Universit o , a y general, Begin Igno So Begin So e.g. .cpp e.g. i.e. \line" our attern attern e.g. P P { { { { { { { { Default Y  The A Solution Ma In As switch anderbilt anderbilt         OO OO V V 53 55 Schmidt Schmidt roblem, C. C. p structure to the Douglas Douglas cont'd at view lo ok rithmic Solution algo instead the rces! but Mo del fo of TYPE top-level the Line_Ptrs data, Array r Class o View Adapter Sort using Sort_AT System interactions! resolve TYPE of to e rithms C++ Table

their Access rithmic & algo mistak design Adapter Sort_AT on . Sort Algo . the Input ARRAY . y y grand fo cus Sort rticipants, the Examples Examples pa Universit Universit TYPE design its Don't Structure op-level GLOBAL attern attern Options Stack T P P { { Avoid the STRATEGIC TACTICAL anderbilt anderbilt COMPONENTS  COMPONENTS OO V OO V 52 54 Schmidt Schmidt space C. C. etc. Douglas Douglas rts, solution &a; so & Solution streams roach table, I/O space the ARRAY e App lik yp es of r t access sort roblem comp onents Iterato patterns View void options, Solution rdinate mechanisms rameterized design *argv[] pa co o Adapter, class, application/p , rithmic & ARRAY> C++ to OOD ry char argv; the rk o input in acto Algo common , F y classes existing rra argc, a of argc, apply framew General classes function: > e.g. e.g. e.g. main attern attern Reusable template P P { { { Note Identify Implement Recognize sort cout parse_args Input cin anderbilt anderbilt     OO OO // // V V } int { 57 59 1/2 Schmidt Schmidt to C. C. up , Douglas Douglas e.g.  rge eciently la rily input ry . minimize: rbitra . a . rt Eciently rbitra be so a must Comp onents Table can reads rt Input options so everything solution insertion Class manipulation that Access & allo cation visible rt & data ry system ry class rmance & C++ Reading integrates the Array memo quickso perfo globally memo ying to rt Input that Adapter y y So cop an b oth comp onents main rove T , A input of acade imp Examples Examples rt rt Universit Universit Manages e.g. F Integrates Data Dynamic o System Options So So size T Create The rces     1. 2. o attern attern P P { { { { { { { Strategic F Solution Problem anderbilt anderbilt     OO V OO V 56 58 &; Schmidt Schmidt C. C. allo cation &; ; ; ; Douglas Douglas &a; dynamic argv; 1 Sort_AT_Adapter only ARRAY argc, Solution Sort_AT_Adapter const using r ->access_table sort ->access_table fo &, ->access_table &, elds input rt Comp onents & so void *argv[] rmat sized o lines F ry quick Class to char ->parse_args ARRAY> concerns rbitra a of std::istream std::ostream input C++ argc, p ointers re Detailed reads rts ration non-recursive sto y System_Sort::insta nce able y > 1 y operator>> operator<< Examples Examples the main Universit Universit Used Used Eciently & Sto Prototypes Stack Arra Input Access sort cin cout Options::instanc e     actical attern attern P P { { { { T Note // void template void } { int anderbilt anderbilt   OO OO V V 61 63 & Schmidt Schmidt details sort C. C. b ecause exp ect y subsystem b allo cation Douglas Douglas the internal clients rt subsystem buffer. es EOF, otherwise a So = exp ected in mak dynamic '\0'; complex 1 interface = replacing that couldn't the allocated r only System fo interfaces terminator interfaces that another replace to Class of using the int interface rm facade into int set in a a dynamically input , together Input to confo class &input, '\n', to rk a o = rovides w up of p The Returns ; ry-sized atterns higher-level method. Table replaced. const; P interfaces a interface search  classes const; rbitra a rting bytes helper function interface int  use so Access std::istream buffer. lets uni ed de nes of { e from Design the to y y a reads . of replaced size . mak sort incompatible *read *recursive_read . Input , , acade Examples Examples ecient with Number Size Recursive . Reads Universit Universit of Adapter F easier e.g. Provide Convert of e.g. istd::ostreams   // char // size_t // size_t // char // // acade attern attern P P { { { { F Adapter private: }; Eciently class public: anderbilt anderbilt    OO V OO V 60 62 r Schmidt Schmidt C. C. chunk int chunk buffer s, Douglas Douglas into performing or int t, allocate time, buffer a reached input int recursive_read at is copy rmat cont'd o &i, F { EOF entire members...  invoke dynamically Class able hold T character data ; until recursion, to full, Input one the of is reached, std::istream Access all is out The enough ACCESS BUFFER input full. buffer EOF way Read recursive_read search/replace is If recursively. If large On y y buffer[BUFSIZ]; *Input::read 1. Initialize *Input::recursive_ rea d 1.a 1.b 2. Examples Examples Universit Universit // char // return // // // // // // // attern attern

P P char { } char } ACCESS ARRAY ACCESS anderbilt anderbilt OO OO V V r 65 67 of fo & Schmidt Schmidt object C. C. point exp osing facade Douglas Douglas rt global so without aggregate a y an cont'd resentation lines overhead system rt rovide of rep p rted So call the data & so r complexit fo rted the time elements so underlying y function System out access instance, its Optimizations the of in almost rt rint rtition one rse-case reduce p o pa complexit on rtitions w to point to access exp osing pa only of y rger fast a y initialization to la atterns space w stack Quickso selection has r single P o small y a n runs a a r without w rt fo pivot class robabilit it log so a options p rt explicit y y 3 a \pushes" to so rovides rovides of p Design an p ys r a , , Examples Examples resentation Universit Universit ranteed rogram rep e.g. Ensure p Provide sequentially access e.g. Insertion Uses Reduces Alw attern attern     P P { { { { Singleton Iterato Non-recursive Median Gua Insertion anderbilt anderbilt   OO V OO V 1. 2. 3. 4. 64 66 can from them o Schmidt Schmidt w e C. C. t data mak Table the Douglas Douglas & r that rdered" o objects one, so Access data cont'd y used: y b ry b ehavio rt re each a create \almost y So used to rbitra rdering a o rting rst-case complexit rithms o Ptrs so y rithm w rting r implementation needed algo complexit so fo encapsulate time System its Line Algo avoid determine in y of rting time to to rt complexit from so selection rithms, y rst-case ecient ecient resources So o of w used lines of time algo pivot o & re complexit atterns use space space yp es w a of t t P & & o initialization complexit average-case abstraction w t rst-case space ring rt exible assembly n o , an family so time time w average- n w y y rt space a log Design subsequent compa allo decouple indep endently , , , Examples Examples ry Universit Universit ry Highly O1 Highly On2 Olog Optimizations On On2 eciency Centralize e.g. their va interchangeable e.g. e.g. Decouple De ne Quickso Insertion r { { { { { { { { acto o attern attern P P { { { { { { F F Bridge Strategy 1. 2. anderbilt anderbilt     OO OO V V 69 71 all use them Schmidt Schmidt ts e C. C. that mo difying of of size mak Three Three Douglas Douglas Median Median & clients one a without one, from rcing value fo each P ivot

attern Strategy get_pivot() pivot P Random Random a attern P without rces indep endently fo encapsulate ry va selecting r Strategy wing interface fo First Select Strategy rithms, rithm rithm all follo the algo ts algo algo the p olicies The rt of the size the Using lets resolves one family quickso a y y extend a to main Examples Examples w pattern Universit Universit it Strategy implementation Provide Ho the De ne interchangeable  quick_sort quick_sort attern attern P P { Intent This 2. 1. anderbilt anderbilt pivot_strat->get_pivot (array, lo, hi)   OO V OO V 68 70 Schmidt Schmidt C. C. rithm pivot Douglas Douglas algo value di erent attern selection P pivot alue a using V etc. pivot the three, selecting Pivot Strategy r of eciently a fo select re the to mo Strategy of median Concrete rt rithms Strategy C so algorithm_interface() algorithm_interface() y algo pattern Selecting ma rithms rious STRATEGY va Concrete Structure input Strategy B algo Strategy y y re algorithm_interface() randomization, a , the Examples Examples Universit Universit e.g. Use selection There Di erent rces  Concrete Strategy A o attern attern Context P P { { { Solution Problem F algorithm_interface() anderbilt anderbilt    context_interface() OO OO V V 73 75 y" the rra . Schmidt Schmidt \a C. C. . rt discourage . the rogram so update complex, p Douglas Douglas and & is rt can reference TYPE ab out so pivot e w by attern the to trait rone, P ys hi; p values { & function rra r a Interface lo, passed the of erro size, simplify assumptions rt sort PIVOT_STRAT> to = be relative So few yp es Strategy use, t the a array, hi] of to es reorder class metho ds, use the pivot limit *pivot_strat should patterns rd to mak Simple can rily ha a only re accordingly... 'hi' ARRAY, a &array, simple rbitra & array[lo, Adapter a be operator[] & rting to reuse 'hi' implementation so ARRAY::TYPE rts , & 'lo' PIVOT_STRAT & ant { ARRAY Devising y Implementing the interface w get_pivot acade should get _pi vot // typename // // Universit Universit so e e.g. fo Conceptually W Use it Although interface Complex extensibilit for }  attern attern P P { { { { { } quick_sort Solution template Problem Key anderbilt anderbilt    OO V OO V 72 74 Schmidt Schmidt C. C. rt Douglas Douglas quickso ; attern > P = . non-recursive Stack SIZE> Strategy deletes with { ->pivot_strat the *pivot_strat use r safety. size_t &new_item; fo pivot_strat; \context" Fixed-size ARRAY> T, T r &array of ; stack array; &item; rticula = temp, size exception const pa pivot_strat; T ARRAY temp; Implementing :: ma ke_ pi vot holder stack_[SIZE]; Universit Universit Pivot_Strategy std::auto_ptr // ARRAY bool quick_sort // bool // T size_t array bool attern attern P P template void template ARRA De nes class { public: private: }; } anderbilt anderbilt   OO OO V V 77 79 rt can so Schmidt Schmidt & C. C. the of Douglas Douglas rts coupling pa ro cessing roblematic p system p attern many P be to option Pro cessing can increases acade global F C++ be in centralize riables Option the va to must of objects global pattern of static options Facade Facade use of Centralizing Structure Singleton y y encapsulation the rces Examples Examples Universit Universit fo rogram Command-line p Unrestricted violate Initialization VISIBLE Use HIDDEN attern attern P P { { { { Problem Key EXTERNALLY Solution anderbilt anderbilt    OO V OO V 76 78 Schmidt Schmidt C. C. element complex subsystem & rily Douglas Douglas the subsystem es rbitra a a metho ds, in mak and size that & attern P interfaces ecient of rces: attern interface fo be P set acade a to F ARRAY ARRAY operator[] wing to rt Sort Sort Insert Insert acade the follo F higher-level interface supp o ARRAY ARRAY the ARRAY ARRAY a clients interface to Sort Sort Sort Sort Using Quick Quick sort implementation need use resolves uni ed de nes the to a ecting y y a the only , ws acade Examples Examples pattern Universit Universit TYPE easier TYPE F e.g. TYPE Provide Allo Simpli es without  { attern attern VISIBLE

HIDDEN Stack Stack P P { Intent This 2. 1.

EXTERNALLY anderbilt anderbilt   OO OO V V 81 83 Schmidt Schmidt C. C. Douglas Douglas }; }; FIRST attern 010 order P 02, = = *argv[]; octal RANDOM, bitmasks! NORMAL in Class char as Singleton NUMERIC ; 04, MEDIAN, = them options argc, stored 01, the { = Options of use are visible int *instance REVERSE can FOLD { we globally options Structure Options y y that Pivot_Strategy parse_args Option Options These so Examples Examples manages Universit Universit if (unique_instance_ == 0) unique_instance_ = new Singleton; return unique_instance_; if (unique_instance_ == 0) unique_instance_ = new Singleton; return unique_instance_; Singleton Singleton enum // // static bool enum attern attern P P class { public: This anderbilt anderbilt static instance() singleton_operation() get_singleton_data() static unique_instance_ singleton_data_ static instance() singleton_operation() get_singleton_data() static unique_instance_ singleton_data_  OO V OO V 80 82 of rst Schmidt Schmidt on C. C. p oint ell-de ned w only Douglas Douglas & to global a rted sta riables rovide va p has implementation attern P & attern rogram \global" rces: p P Singleton fo of instance, of after Singleton wing use one & done follo the is only Singleton the sub classing has creation Using rent resolves the class encapsulation it if (unique_instance_ == 0) unique_instance_ = new Options; return unique_instance_; if (unique_instance_ == 0) unique_instance_ = new Options; return unique_instance_; initialization y y a to transpa w Examples Examples pattern Universit Universit Ensure access Lo calizes Ensures objects Preserves use Allo attern attern P P { Intent This 1. 3. 2. 4. Options Options anderbilt anderbilt static instance() bool enabled() field_offset() static unique_instance_ options_ static instance() bool enabled() field_offset() static unique_instance_ options_   OO OO V V { 85 87  the Schmidt Schmidt C. C. EOF; during { != Douglas Douglas complex implementation op eration *argv[] from OPTION ~OPTION rison somewhat risons |= &= char is compa cont'd interface ``nrfs:k:c:t:'' of ab ove WORD WORD argc, Compa rate yp e wn t Options::FOLD; Options::NORMAL; Options::NUMERIC ; Class change argv, sepa int sho the r to OPTION OPTION argc, shouldn't Options op erato Simplifying pattern { options_, options_, options_, determine { phase rison to . getopt interface 'n': . c; c Bridge y y = . compa CLR_BIT SET_BIT break; CLR_BIT SET_BITWORD, CLR_BITWORD, the the b etter c Examples Examples Universit Universit case } // int Options::parse_ar gs The It's But initialization Use rces switch o attern attern P P { { { { Problem F Solution for anderbilt anderbilt    } define define bool OO V OO V 84 86 { Schmidt Schmidt C. C. . const . 0; Douglas Douglas . < 0; 0; &rhs *r; < < r: ; bitmask char BOL. rhs.bof_ op erato Class Bridge Line_Ptrs Options::FOLD rhs.bof_ rhs.bof_ cont'd from const rison options Singleton. using Options::NUMERIC ; // ; *l, on Options compa const Class Offset Options::NORMAL later this->bof_, Singleton. char the Options::instance o; // Maintains = sort this->bof_, this->bof_, roach // ; Options Using *instance_; pivot_strat Ensure const app options->enabled Option // if strcasecmp strcmp numcmp options->enabled *options implement y y another ; to if // Options options_; y a options->enabled enabled see Examples Examples Line_Ptrs::opera tor < return return return w Universit Universit field_offset_; field_offset *compare else else Options if e'll attern attern P P One int } W int static Options u_long bool int Pivot_Strategy int anderbilt anderbilt   }; OO protected: OO V V 89 91 { Schmidt Schmidt C. C. . . const . Douglas Douglas &rhs sort y attern indirection b P call attern call used P r 0; Line_Ptrs Concrete Concrete method_impl() ->compare < Bridge function function ImplementorB ImplementorB method_impl() op erato Implementor Implementor Bridge of the concise virtual of rison the level a re rhs.bof_ to mo compa extra Concrete Concrete method_impl() Using an the ImplementorA ImplementorA much bof_, is 1: method_impl() Structure is equivalent *Options::instan ce y y there's is wing Examples Examples solution Line_Ptrs::opera tor <c on st Universit Universit follo ever, w Which return method() attern attern P P { } This The Ho int anderbilt anderbilt Abstraction Abstraction    OO V OO V , 88 90 & can op en o Schmidt Schmidt w C. C. t building & the Douglas Douglas when closed that implementation rise so b oth strcasecmp() a is r< o that at that Options Options compare() attern er p P bu er rces attern fo P implementation interface changes numcmp() Table its wing rm Bridge y co de follo Bridge from unifo Line_Ptrs::o the Access the r direct 1: compare() The fo the stable, extensibilit a strcmp() Using w re revent abstraction a p resolves w allo an simplify counting to rovide y y to soft p to to indep endently pattern Examples Examples , w w Universit Universit ry Op en Closed operator< Ho i.e. reference Ho va Decouple { { attern attern P P { extensible This Intent 2. 1. Line_Ptrs Line_Ptrs anderbilt anderbilt   OO OO V V 93 95 sort C++ Schmidt Schmidt C. C. b ecause exp ect the the Douglas Douglas with clients with otherwise Table Table interface couldn't attern P Access Access attern that another P rces: the the fo into TYPE TYPE TYPE ::TYPE together Adapter wing class rk a Adapter o ARRAY ARRAY ARRAY operator[] size() ARRAY:: operator[] size() integrate integrate follo the w of rs

Access_Table make_table() length() element() make_table() length() element() the interfaces The

"conforms to" rently rently classes Using op erato interface lets

resolves "conforms to" transpa transpa the y y Line_Ptrs Line_Ptrs to to incompatible Examples Examples = array[i] w w pattern Universit Universit of Adapter ARRAY ARRAY Ho routine Ho istd::ostream Convert  1: ARRAY::TYPE t sort sort attern attern P P { This Intent 1. 2. typedef Line_Ptrs TYPE make_table() operator[] size() typedef Line_Ptrs TYPE make_table() operator[] size() anderbilt anderbilt Sort_AT_Adapter Sort_AT_Adapter   OO V OO V 92 94 on Schmidt Schmidt which C. C. on assigned? later r place *right; Douglas Douglas r get one op erato in char overhead dep ending , attern rison Op erato P details const reduce to compare compa time rison r fo the front *left, over p ointer-to-metho d Adapter up initialization Compa rk char the o choices initialize w Adaptee change Adaptee specific_request() ab out of y the to compare ma rry much o const request() Target Target w di erent as the pattern to details do ry enabled many ant Structure to re w y y e Initializing a re 2: specific_request() acto 1: request () do es a F lik *compare a only Examples Examples w Universit Universit e'd e Ho Initialization W W int options There Use rces o attern attern P P { { { { { { Problem F Solution client client request() Adapter Adapter anderbilt anderbilt    OO OO V V y 97 99 b Schmidt Schmidt C. C. exp ected Douglas Douglas buffer. 0; element. array. T. = to interface bu er of counted Class data array *buffer ARRAY Class Ref const; access_array. the is to reference the // char in sort. & the able to Access_Table. T by table of Adapter rm Return lines, T Reference // elements A used field/column. confo Access // Length Line_Ptrs & rt to Access // // onto size_t const; So initializing ; able line T index; The { *access_table_impl_; for memory. operator const T> { const; indices The void of *bof_;  make_table Access y y Method buffer size_t maps access_array_; &array the int ~Access_Table Access_Table_Impl virtual // // virtual T size_t Array anderbilt anderbilt   protected: }; template class public: OO V OO V struct }; 96 98 Schmidt Schmidt C. C. Douglas Douglas Table count class pattern Class virtual count Access the y are Impl the Bridge from deletion. y Constructor reference Arra b constructor methods. the reference // able use of buffer T buffer tracks r subclasses fo buffer Set y Part void; Decrement Get iterator //Default // rra Dynamic Increment // *buffer; // // a STL { ensures Refcount Access // 0; index; *; = // // Underlying void; char T> size; void; The // const; size void; riable-sized  const; y y destructor va const; { size_t  a ~Access_Table_Impl  . size_; ref_count_; int Line_Ptrs element size Examples Examples Universit Universit Sort_AT_Adapter::siz e these Sort_AT_Adapter These Factory Factory Product Product make_product() attern attern Put P P return Line_Ptrs size_t // private virtual typedef anderbilt anderbilt creates creates size_t Line_Ptrs { }; // OO class V V public: OO 105 107 API use each Schmidt Schmidt decide of C. C. the to 0; Douglas Douglas rm { subsequent on sub classes sub classes b eginning its cont'd s2, confo to s2 let later to * from but attern strtod char attern re-caching P p olicies = p Table P function y object, instantiation ry b d2 rces: options an fo const 1; acto defer 0, Access adapter F wing rmance Metho d *s1, initialization the -1; class creating s1, the ry a follo of d2 return r perfo fo char command-line p ointer-to-function the lets == change numcmp acto d2 return a F to Using > strtod instantiate new d1 r = to d2 0; const interface fo resolves Metho d write d1 if initialization subsequent compare easier < d1 y y ry line an adding to it class if // the , & es y d1 roves acto Examples Examples Co de b pattern return numcmp Universit Universit F e.g. need Decouple which De ne Imp eld Mak if else else double   e attern attern P P { { { { } int used Intent This W anderbilt anderbilt    OO V OO V 104 106 rsed Schmidt Schmidt pa C. C. re a initializing ro cessing Table is p Douglas Douglas on options rogram Access p attern later rt *argv[] P able the subsequent so T applications ry rt char p olicies a ect command-line system acto initialize to F non-so Access to argc, after in whole the details the the done initialization able Options::NUMERIC  Options::FOLD int pattern T of is rts Using Options::NORMAL  &strcmp; &numcmp; &strcasecmp; r pa change = = = Access Metho d fo to initialization ry Initializing the Table ant initialization nastiest w acto easier Co de F y y using this->enabled this->enabled it the wing . . , of the es don't Access rces . if if . Examples Examples Universit Universit e e.g. fo follo . . this->enabled Options::parse_ar gs Mak Use One W the  this->compare this->compare this->compare attern attern P P { { { { The Solution Problem Key // else else // if anderbilt anderbilt     { bool OO V V OO 109 111 Schmidt Schmidt C. C. able initializes T Douglas Douglas that attern P Access num_lines, r Metho d *buffer fo ry ownership. acto Metho d char F size_t a attern ry Access_Table. num_lines; Obtain P has // acto F class op. Initialization the TYPE TYPE ry Metho d initializes buffer; 0; ry acto = F = acto able F Method assignment make_table() = 0

Access Table T count Line Ptrs Line Ptrs y y // initialize the table // initialize the table Adapter the T Implementing Array Examples Examples A Access Sort_AT_Adapter: :ma ke_ ta ble Universit Universit Factory // this->access_arr ay _.r esi ze this->buffer_ size_t rt attern attern Using P P The So // int { Sort AT Sort AT Adapter Adapter anderbilt anderbilt  make_table() OO V OO V 108 110 Schmidt Schmidt C. C. Adapter &at AT Douglas Douglas the r attern fo Sort P the attern P ; Sort_AT_Adapter Metho d initializes Access_Table<>. ry Adapter &is, buffer. is; buffer; T acto Metho d A F Adapter ry rt return new Concrete_Product into return new Concrete_Product Creator Creator Concrete Concrete the factory_method() Product *product = factory_method() return product Product *product = factory_method() return product input.replaced So initializes acto

Creator = of F input.read stdin factory_method() = 0 make_product() num_lines, std::istream = istd::ostream the

CREATES Method y y entire wing num_lines Structure input; table Using *buffer Examples Examples follo Universit Universit Factory Read operator>> attern attern P P access The Product Product Product char size_t // Input // Product at.make_table Concrete Concrete anderbilt anderbilt  { } void OO V V OO . 113 115 the . each Schmidt Schmidt w . without C. C. kno able to T Douglas Douglas field accessing Bu er {  having next from Access Input num_lines; \& bu er the *buffer, the without with line decoupled cont'd size_t char able initialize T be able to next through T y a of attern w often scan resented Access P a r to rep can the collection is Access . . r o rovides . . p resented pattern beginning . . the details Iterato bu er r rep initialize lp; // // is the to pattern Line_Ptrs_Iter::cu rre nt _el em ent = = container w lp; r e Iterato y y a ho lik bu er in the rce resentation Determine Examples Examples Universit Universit e'd fo Iterato Initializing wing Rep item Use W input Line_Ptrs // lp.bol_ lp.bof_ return attern attern P P { { { Key Solution Line_Ptrs kno Problem Line_Ptrs_Iter::Li ne _Pt rs_ It er } The anderbilt anderbilt     OO V OO V 112 114 Schmidt Schmidt object C. C. pattern, r ; cont'd Douglas Douglas ; iterato aggregate the an attern resentation on P args.begin of rep = fields num_lines; line_ptr; j based determine & [i]; = & Metho d attern elements heavily underlying argv { lines P { is buffer, ry r its 0; the of buffer iter.current_ele me nt ++i args; == = acto iter STL the F ++j *argv[]  ry Iterato endl; access exp osing argc; ra ; std::string  the << < char to Lib beginning i line_ptr y rd through a 1; without *j_ argc, w the = go. args.end a << i y y Standa != int iter.is_done iter.next Line_Ptrs_Iter j Iterate where must cout std::vector: :it era tor args.push_back int Examples Examples this->access_arr ay_ [co un t++ ] Line_Ptrs Universit Universit C++ main Provide sequentially } // // // for { } for std::vector for Implementing attern attern P P { } } Intent The e.g., int anderbilt anderbilt   OO V V OO r, 117 119 Schmidt Schmidt C. C. system y mo dula minimizes a Douglas Douglas UNIX inlining extensibilit Study &a; structure & argv; existing and to &p; to Case yp es rces routine: t ARRAY fo argc, rt rable Solution ARRAY ey this k abstraction, So r techniques of , sort fo y compa rit OO const rm is many rameterized o void int rt F *argv[] pa so system &o, System using e use-case mo dula lik resolve of char ->parse_args to ARRAY> ARRAY> system ry ARRAY ecient general General a help illustrates increased our features argc, is of highly const y y from Summa study C++ & wing y int enabled , routine y so a rder ,  , rt w Iterato ha Case checking so a the examine r is a of fo std::ostream std::ostream rces e'll .begin .end .begin .end  fo w y y input rovides p re, the useful solution output whether r Examples Examples , lp.bol_; is Universit Universit riginal b efo at.array std::::ostream_iterat or< Syst em_ Sor t:: Lin e_P trs> at.array at.array at.array std::::ostream_iterat or< Syst em_ Sor t:: Lin e_P trs> i.e. o The Options::instance << operator<< operator<< erify std::copy std::reverse_copy attern attern P P { { Iterato V resolve This As else if os anderbilt anderbilt     } } void void OO V V OO of 121 123 Schmidt Schmidt C. C. multiple integrals & rop erties p Douglas Douglas across on families" items of design 4 0 7 18 r rogram 8 0 4 15 dep ending \p , 0 13 13 13 numb er of and/o ry values . 0 4 18 13 . to ;- . . 0 8 15 15 new . . co de Problems . . 4 0 7 necessa 18 cont'd use example . add 0 4 data 13 13 relation be use , much data rt 7 0 4 8 rted rces in values so will as so o simple e.g. out r F a uted to values uted Common uted, but small unsorted perm not sorted sorted and sorted, but reuse fail erroneously zero not p erm p erm app ea roblems: re y y y p a duplicate to examined, ma ma ma p ossible will duplicate no illustrates ant it as w y y values . has has implementations b eing e . common routine routine routine w . roblem Examples Examples , p rt rt rt Universit Universit data though data data data So So So i.e. solutions if if use if  attern attern P P { { { { Several This Multiple the 3. 1. 2. anderbilt anderbilt    OO V OO V y 120 122 . rst ma . must Schmidt Schmidt . it C. C. the in which -1 , rithm rrect, rt Douglas Douglas == co so algo is to rting than so consecutively cont'd solution ; routine our check rrect" times ecient to rting \co that so a Solution many rces endl; endl; of time space potentially_sort ed , rdians? o of rrect F re & , << << run chance gua co mo a rm be optimizations custo des? the e o time the y existence F tak rd ma rove ipsos failed" worked" the space b oth writing original, gua not imp be to than potentially_sort ed. be gin original.end routine shall General "sort original.begin "sort certain assume y y should re, costo diet should this << input; << it Who , potentially_sort ed ; Examples Examples simpler  Universit Universit Quis >> cannot check_sort e.g. place! Also, facilitate Therefo be  e cerr cout attern attern P P { { { Solution W if cin sort std::copy else anderbilt anderbilt   OO V V } OO 125 127 Schmidt Schmidt C. C. binding function Douglas Douglas dynamic memb er & space the with roach if implementations order App solution see here rithm in inheritance & to multiple rganization &original, o Algo yp es, t Solution check ADT rdinate ARRAY actually application duplicates Metho d co o patterns ARRAY> is the ry to OOD in &potential_sort sanity rameterized rk remove High-level structure const acto o design detect pa F & rch & ARRAY basic sea TYPE TYPE r fo &; Hash Hash Table Table *instance TYPE TYPE interfaces ARRAY Dups Dups Binary Binary Search Search Diagram TYPE TYPE Class ARRAY> const

Struct Search class Class method. ry C++ Method TYPE TYPE y y acto Search_Strategy Binary Binary Search Search Nodups Nodups Examples Examples Universit Universit LONG LONG Singleton Factory make_strategy attern attern P P Strategy // static // virtual Range Range Vector Vector anderbilt anderbilt  template }; Search_Struct { public: OO V OO V 128 130 Schmidt Schmidt C. C. 0; Douglas Douglas = 0; = then srchstrct cont'd from 0; Interfaces &existing_item &new_item rithm loop loop = succeeds then T T 1 1  structure, - - Algo Class fails check const const size size original[i] class. search ERROR T> C++ to to potential_sort[i ] srchstrct 0 0 sanity base remove SUCCESS ERROR insert High-level < < remove srchstrct into i i return y y insert if bool ~Search_Strategy if bool

rithm algo sort check . .

the difying mo without rted so is y rra a an /* /*

if checking r fo strategies the extends pattern This  cont'd ARRAY::TYPE> Binary_Search_Dups

TYPE; TYPE; Nodups

Dups

Search

Search

class Binary Vector Binary

interfaces Range

TYPE TYPE

Table

Hash long ARRAY>

Class ARRAY::TYPE ARRAY::TYPE T> TYPE

:

Strategy

Struct

C++ check_sort Search typename TYPE

attern P Strategy the Using template attern P }; class { }; template {

o D Examples attern P OO anderbilt OO V 132 134 used Schmidt Schmidt decide re C. C. a Douglas Douglas */ . patterns sub classes sub classes . to let . eri er but /* Strategy V cont'd & ARRAY::TYPE> rt , }; So object, TYPE; instantiation */ in an . : defer Singleton . , r interfaces . class creating specialization /* atterns a r Iterato : ARRAY> ARRAY::TYPE P fo , Class lets TYPE; instantiate acade F template C++ to Design interface Metho d long typename the Search_Strategy Douglas Douglas attern P unction F rt ARRAY::TYPE> so ->make_strategy Metho d strategy  { ry check acto int F veri cation the &orig, &p_sort rt p_sort.size the so != ARRAY> of the return new Concrete_Product return new Concrete_Product ARRAY ARRAY Creator Creator Concrete Concrete r factory_method() Product *product = factory_method() return product Product *product = factory_method() return product  fo Creator factory_method() = 0 make_product() Search_Strategy< typ en ame const co de const -1; < y y CREATES Implementing ::i ns tan ce attern attern P P e.g. if auto_ptr Product Product Product Concrete Concrete anderbilt anderbilt  check_sort template OO V OO V 136 138 Schmidt Schmidt decide C. C. Douglas Douglas sub classes sub classes veri er rt to let so attern P but the attern P in object, instantiation rce: Metho d an fo strategy defer ry Metho d wing ry class acto creating a follo F r acto fo initialization F the lets Strategy Strategy return new New_Search_Struct return new New_Search_Struct the New Search make_strategy() New Search the instantiate Search Strategy The

to make_strategy() interface resolves Metho d Using CREATES y y extend ry an rently class to acto Examples Examples w pattern Universit Universit F Ho transpa De ne which  attern attern Struct

Search Struct Search Struct P P { This Intent 1. anderbilt anderbilt   New Search New Search OO V V OO 141 143 rs Schmidt Schmidt C. C. 1] 1] - - ecto V ++i Douglas Douglas 1] 1] * - ; - Range r - fo * 1] Structure - potential_sort[i potential_sort[i rch { == ++i == Sea potential_sort[i potential_sort[i Structure < >::make_strategy < size; ARRAY::TYPE> potential_sort.si ze the Search_Strategy rch < < > i i &potential_sort Sea 0; ARRAY> 0; 1; 1; = = = = the potential_sort[si ze potential_sort[0] ; &potential_sort i i Initializing 0; = 0; potential_sort[i ] potential_sort[i ] y y if Metho d potential_sort[i ] range potential_sort[i ] Examples Examples ry Universit Universit ++duplicates; return duplicates size_t duplicates size_t return ++duplicates; if else if else acto attern attern Sp ecializing P P F long int for const int for const anderbilt anderbilt  template Search_Struct { template Search_Strategy:: ma ke_ st rat eg y OO V OO V 140 142 Schmidt Schmidt C. C. 1] . - Douglas Douglas . cont'd . long cont'd memory ++i ARRAY::TYPE> unction F typeid ++i the ; duplicates false rt == Structure ; false so == potential_sort[siz e == potential_sort[ 0], rch &hash_function; deletes 0 check Sea == p_sort.size orig.size the the < size, < p_sort[i] orig[i] i size 2 Hash_Table 0; Range_Vector Binary_Search_Dup s< ARR AY > <= 0; new = potential_sort[ 0] -1; = -1; new i new new i y y duplicates size range 0; Initializing if if return ss->insert ss->remove Examples Examples Universit Universit int && return int return Implementing typeid auto_ptr's return return return if if attern attern P P else else for if else for // return anderbilt anderbilt OO V V } } OO a 145 based Schmidt C. strategy structure the Douglas to run-time & at Study objects co de techniques selected Case is OO existing strategy use simpli ed eri er the is a ect to V structure solution w rt into not rch ho rithm So sea do es algo of ecient pushed & ry ADT is pattern illustrates y ry solutions riate ro cessing p facto rop y new Summa veri er Strategy extensible, complexit app r, main rt Examples the so Universit selection Adding on The The The attern P { { { { mo dula The anderbilt  OO V 144 rs Schmidt C. 1] ecto V - Douglas Range r fo duplicates potential_sort[siz e potential_sort[ 0], Structure &hash_function; 0 rch == size, Sea 2 Hash_Table potential_sort; potential_sort,  the size Range_Vector Binary_Search_Nod up s Binary_Search_Dup s< lon g> new <= new new new y duplicates size if if return Examples Universit range return return return attern Sp ecializing P if else else else anderbilt OO V }