, 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++
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,
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:
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
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
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_
Struct Search class Class method. ry C++ Method TYPE TYPE y y acto Search_Strategy 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 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