Design Patterns. Patterns.mkr Page 223 Wednesday, August 25, :17 AM

Size: px
Start display at page:

Download "Design Patterns. Patterns.mkr Page 223 Wednesday, August 25, :17 AM"

Transcription

1 Patterns.mkr Page 223 Wednesday, August 25, :17 AM Design Patterns n the earlier hapters, we have seen that a entral goal of objet-oriented programming is the support of ode reuse. This hapter examines the tangential, but equally important onept of idea reuse: the reuse of basi programming and design tehnique, rather than the reuse of atual ode. Many of these tehniques are known as design patterns. n this hapter, we will see: Why design patterns are important Several examples of objet-based design patterns, inluding the Funtor, Adapter, Wrapper, terator, Composite, and bserver patterns. Some sophistiated C++ programming triks A brief disussion of objet-oriented (inheritane-based) design patterns. Although software design and programming are often diffiult hallenges, many experiened software engineers will argue that software engineering really has only a relatively small set of basi problems. Perhaps this is an understatement, but it is true that many basi problems are seen over and over in software projets. Software engineers who are familiar with these problems, and in partiular, the efforts of other programmers in solving these problems, have the advantage of not needing to reinvent the wheel. The idea of a design pattern is to doument a problem and its solution so that others an take advantage of the olletive experiene of the entire software engineering ommunity. Writing a pattern is muh like writing a reipe for a ookbook; many ommon patterns have been written and rather than expending energy reinventing the wheel, these patterns an be used to write better programs. Thus a design pattern desribes a problem that ours over and over in software engineering, and then desribes the solution in a suffiiently generi manner as to be appliable in a wide variety of ontexts. ike a reipe, design patterns usually follow a format. There are several formats for designing a pattern. Typially, a design pattern onsists of:! " # $ %&! " ' ( $ ) & * +!, -. ' - ) # # / $ " ) 0! $ ' 1 ) 0! $ %1 " ) 2-3 ' $!! 1 4 % 1!! $ * %1 4 5 ' 1 -.! 1! * " # $ %&! " -.! " ) +/ - %) 1 %1 ' " / 2 2 % # %! ! * 1! $ %#, ' 1 1! $ ' " - ) &! ' ( ( + %# ' & +! % 1 ' 3 %! 0 ' $ %! - 6 ) 2 # ) 1 * -! 7 - " 8

2 M \ ] Patterns.mkr Page 224 Wednesday, August 25, :17 AM 9 9 : 1. The pattern name. 2. The problem, inluding a speifiation of the problem the pattern solves, an explanation of why this problem is important, some appliations of the problem, and examples of known uses. 3. The solution, inluding a desription of the lasses in the patterns, possibly with a struture diagram, a generi (language independent) implementation of the pattern, with language-speifi issues as appropriate, and sample ode. 4. Consequenes, inluding the results and trade-offs, of using the pattern, and a disussion of related patterns. n this hapter, we will disuss several patterns that are ommonly used in objet-based data strutures. ur pattern speifiations will not be as formal as disussed above, but where reasonable, we will provide some ode, and pointers to the use of the pattern elsewhere in the text. Toward the end of the hapter, we will see some objet-oriented patterns. ; < = A = >? C D E? F n Chapter 3, we saw how funtion templates an be used to write generi algorithms. As an example, the funtion template in Figure 5.1 an be used to find the maximum item in an array. G G // Generi findmax for Comparables; uses natural order. // Preondition: a.size( ) > 0. template <lass Comparable> onst bjet & findmax( onst vetor<comparable> & a ) int maxndex = 0; Q RS T U V W X Y for( int i = 1; i < a.size( ); i++ ) if( a[ maxndex ] < a[ i ] ) maxndex = i; return a[ maxndex ]; Z [ \ [ ] ^_ findmax [ _ d j o \ p q j [ j d e [ ^ ab ] \ m n ] ^d e f g h d q ] a ] i j ] p [ ] ak l Comparable

3 M G \ [ q a Patterns.mkr Page 225 Wednesday, August 25, :17 AM G G G G G G M G P G M // A simple retangle lass. lass Retangle publi: Retangle( int len = 0, int wid = 0 ) : length( len ), width( wid ) int getength( ) onst return length; int getwidth( ) onst return width; r e [ s q \ _ d void print( ostream & out = out ) onst out << "Retangle " << getength( ) << " by " << getwidth( ); private: int length; int width; ; ] t s q \ _ d ^ ostream & operator<< ( ostream & out, onst Retangle & rhs ) rhs.print( out ); return out; Q RS T U V W X x Retangle _ j j d e q a \ _ d ^ operator< l d p [ j \ d e y f [ \ ^ \ b l \ u [ _ d j v 9 9 w m n owever, the template has an important limitation. That is, it works only for objets that have an operator< funtion defined, and it uses that operator< as the basis for all omparison deisions. There are many situations in whih this is not feasible. As an example, onsider the Retangle lass in Figure 5.2. The Retangle lass does not have an operator<. The main reason for this is that beause there are many plausible alternatives, it is diffiult to deide on a good meaning for operator<. We ould base the omparison on area, perimeter, length, width, and so on. As we saw in the Shape example in Setion 4.3, one we write operator< as a member funtion, we are stuk with it. Even without operator< as a member funtion, we ould still write a twoparameter nonmember operator<, and separate the omparison from the retangle lass. Thus eah time we write a new program, the program an speify its own version of operator<. This is a slight improvement, but we an write only one operator< for the program. What if we want to have findmax work with several different omparison alternatives?

4 M G d ] \ b l Patterns.mkr Page 226 Wednesday, August 25, :17 AM 9 9 z G G G G G G M G P G M P G // Generi findmax, with a funtion objet. // Uses a named method in the funtion objet. // Preondition: a.size( ) > 0. template <lass bjet, lass Comparator> onst bjet & findmax( onst vetor<bjet> & a, Comparator omp ) int maxndex = 0; for( int i = 1; i < a.size( ); i++ ) if( omp.isessthan( a[ maxndex ], a[ i ] ) ) maxndex = i; return a[ maxndex ]; // Compare objet: ordering by length. lass essthanbywidth publi: bool isessthan( onst Retangle & lhs, onst Retangle & rhs ) onst return lhs.getwidth( ) < rhs.getwidth( ); ; int main( )... out << findmax( a, essthanbywidth( ) ) << endl;... Q RS T U V W X f ~ ~ [ ] [ a q \ _ d ^ l [ ] l p ^ \ y a [ _ d d e m n d p [ j \ d q j [ q \ _ d ^ \ _ a a The solution to the problem is to pass the omparison funtion as a seond parameter to findmax, and have findmax use the omparison funtion instead of assuming the existene of an operator<. Thus findmax will now have two parameters: a vetor of bjet (whih need not have any operator< defined), and a omparison funtion. The main issue left is how to pass the omparison funtion. Some languages, inluding C++, allow parameters to be funtions (atually they are pointers to funtions). owever, this solution often has effiieny problems and is not available in all objet-oriented languages. nstead, a solution that works in all objet-oriented languages is to use a funtion objet. The funtion objet is sometimes known as a funtor.

5 M l \ Patterns.mkr Page 227 Wednesday, August 25, :17 AM r e [ s q \ _ d ] t s q \ _ d ^ \ u [ _ d j v 9 9 m n G G G // Generi findmax, with a C++-style funtion objet. // Preondition: a.size( ) > 0. template <lass bjet, lass Comparator> onst bjet & findmax( onst vetor<bjet> & a, Comparator isessthan ) int maxndex = 0; Q RS T U V W X for( int i = 1; i < a.size( ); i++ ) if( isessthan( a[ maxndex ], a[ i ] ) ) maxndex = i; return a[ maxndex ]; findmax h ^d e j d ƒ [ k a q \ _ d ^ [ _ d m n The funtion objet often ontains no data. t ontains a single method, with a given name, that is speified by the generi algorithm (in this ase findmax). The objet, whih is simply an instane of the single-method lass is then passed to the algorithm, whih in turn alls the single method of the funtion objet. We an design different omparison funtions by simply delaring new lasses. Eah new lass ontains a different implementation of the agreed-upon single method. An example is shown in Figure 5.3. findmax now takes two parameters. The seond parameter is the funtion objet. As shown on line 11, findmax expets that the funtion objet implements a method named isessthan (speifially, it is expeting that isessthan takes two parameters, both of type ompatible with bjet, for whatever bjet turns out to be). Sine the name of the funtion objet parameter is omp, line 11 alls the omparison funtion by omp.isessthan. What is the type of omp? omp an be any type (that has an isessthan method), so we know its type is a seond template parameter. We use the symboli name Comparator to signify its role. (Funtor would work also, but Comparator is a more speifi name for this funtion objet.) ne findmax is written, it an be alled in main. To do so, we need to pass to findmax a vetor of Retangle objets and a funtion objet that has an isessthan method. We implement a new lass essthanbywidth, whih ontains the required method. That method returns a Boolean indiating if the first retangle is less than the seond retangle on the basis of widths. main simply passes an instane of essthanbywidth to findmax. bserve that the essthanbywidth objet has no data members. This is usually true of funtion objets, and so funtion objets are often passed using all by value. bserve also that when the findmax template is expanded, the type of omp is known. Therefore, the definition of omp.isessthan is also known. An aggressive ompiler an perform the inline optimization of replaing the funtion all to omp.isessthan with the atual definition. n many.! 2 / 1 # - % ) 1 ) &! # - # ) 1 - ' % 1 " ',! -. ) " (! # %2 %! & 6 -.! 4! * 1! $ %# ' + 4 ) $ %-., 8 1 %1 " - ' 1 #! ) 2 -.! # +' " " %" ( ' " "! - ) -.! ' +* 4 ) $ % -., 8 ˆ Š %" ' 1 ) -.! $ 1 ',! 2 ) $ ' 2 / 1 # * - % ) 1 ) &! # - 8 / 1 # - %) 1 ) &! # - " # ' 1 &! ( ' " "! / " * %1 4 # ' ++ & 6 0 ' +/! 8.! %$ # ' ++" # ' 1 &! %1 * +%1! 8

6 M G l \ _ Patterns.mkr Page 228 Wednesday, August 25, :17 AM 9 9 Œ ases, the ability of the ompiler to perform this inline optimization an signifiantly derease the running time. The funtion objet tehnique is an illustration of a pattern that we see over and over again, not just in C++, but in any language that has objets. n C++, there is an additional oding trik that makes the ode look muh prettier in the generi algorithm, and only slightly uglier in the funtion objet s lass. The prettier findmax is shown in Figure 5.4. There are two basi hanges: ine 10 now has the all to isessthan, apparently without a ontrolling objet. isessthan is the parameter to findmax. So it appears that we are passing the method diretly to findmax and bypassing the funtion objet. That is not what is atually happening. nstead, we have used the C++ trik of overloading the funtion all operator in the funtion objet itself. What we mean by this is that sine isessthan is an objet, line 10, whih reads as if( isessthan( a[ maxndex ], a[ i ] ) ) is atually interpreted as G G G G G G M G if( isessthan.operator() ( a[ maxndex ], a[ i ] ) ) // Compare objet: ordering by length. lass essthanbyength publi: bool operator( ) ( onst Retangle & lhs, onst Retangle & rhs ) onst return lhs.getength( ) < rhs.getength( ); ; // Compare objet: ordering by area. lass essthanbyarea publi: bool operator( ) ( onst Retangle & lhs, onst Retangle & rhs ) onst return lhs.getength( ) * lhs.getwidth( ) < rhs.getength( ) * rhs.getwidth( ); ; Q RS T U V W X W r h j d [ _ d j ƒ m n [ k a q \ _ d ^ [ _ d j d m n f ~ ] [ Retangle

7 M G _ a \ ] l f Patterns.mkr Page 229 Wednesday, August 25, :17 AM p ~ d [ ] j \ p Ž ] ~ ~ [ ] j 9 9 operator() is the funtion all operator, muh like operator[] is the array indexing operator. With this mind-blowing piee of C++ syntax, we an implement various funtion objets in Figure 5.5. Figure 5.6 shows a simple main that plaes some Retangle objets in a vetor and then, using the funtion objets of types defined in Figure 5.5, finds the maximum Retangle, first on the basis of length, and then on the basis of area. operator() is the funtion all operator When we implement algorithms, often we run into a language typing problem: we have an objet of one type, but the language syntax requires an objet of a different type. Sometimes a type onversion works. ften we need a little more. For instane, in Setion 4.3, we found that sorting pointers to shapes did not quite work beause operator< is already defined for pointers. Consequently, we needed to define a new lass that stored the pointer and defined a meaningful operator<. G G G G G G M G P G #inlude <iostream> #inlude <vetor> using namespae std; // main: reate four retangles. // find the max, using two different riteria. int main( ) vetor<retangle> a; Q RS T U V W X a.push_bak( Retangle( 1, 10 ) ); a.push_bak( Retangle( 10, 1 ) ); a.push_bak( Retangle( 5, 5 ) ); a.push_bak( Retangle( 4, 6 ) ); out << "argest length:\n\t" << findmax( a, essthanbyength( ) ) << endl; out << "argest area:\n\t" << findmax( a, essthanbyarea( ) ) << endl; return 0; f ~ [ ~ ] f ~ ] ^j b d e q \ _ d ^ d ^ \ j q j d ] a a d [ j findmax h ^d e d h p ^ [ ] [ \ d l l

8 M G ~ b Patterns.mkr Page 230 Wednesday, August 25, :17 AM 9 " - ) $! " ' ( $ %, %- %0! - 6 (! 5 ' 1 ' " ) ( *! $ ' - %) 1 " -. ' - -.! ( $ %, %- %0! - 6 (! )! " 1 ) - " / ( ( ) $ - # ) $ * $! # %" / "! 3.! 1 -.! %1 * -! $ 2 ' #! ) 2 ' # +' " " %" 1 ) -! 7 ' # ' - %" 1!!! 8 This tehnique illustrates the basi theme of a wrapper lass. ne typial use is to store a primitive type, and add operations that the primitive type either does not support or does not support orretly. A similar onept is an adapter lass. An adapter lass is typially used when the interfae of a lass is not exatly what is needed, and provides a wrapping effet, while hanging the interfae (in a manner similar to eletrial adapters). ne differene between wrappers and adapters is that often an adapter is implemented by private inheritane. otie that the implementation via private inheritane is often not available for wrapper lasses that wrap a primitive (and therefore, non-lass) type. This setion illustrates some useful examples of wrapper lasses and also provides an example of an adapter lass. š œ ž Ÿ Ÿ Ÿ Ÿ.! Pointer " - ) $! 5 ' " ' ' - ' 3 %++,!, &! $ 5 ' ( ) %1 -! $ - ) ' Comparable 8 This subsetion illustrates two wrapper templates for pointers. ur first template is based on the shape example. We will use it when we disuss indiret sorting in Setion 9.9. The seond example illustrates a asual implementation of the newly standardized auto_ptr lass. This wrapper is used to add limited destrutorlike behavior to pointers. ª «± ² «³ «ur first wrapper is the lass template, Pointer, shown in Figure 5.7. The Pointer will store, as a data member, a pointer to a Comparable. We an then provide a omparison operator for the Pointer type. G G G G G G M // Class that wraps a pointer variable for sorting. template <lass Comparable> lass Pointer publi: expliit Pointer( Comparable *rhs = U ) : pointee( rhs ) bool operator<( onst Pointer & rhs ) onst return *pointee < *rhs.pointee; operator Comparable * ( ) onst return pointee; Comparable * get( ) onst return pointee; private: Comparable *pointee; ; Q RS T U V W X µ Pointer _ a j j o h e ^_ e h ] ~ j ^ \ d [ ] y ] ^ [ m a l ] j ] d ^ \

9 M m k k \ y Patterns.mkr Page 231 Wednesday, August 25, :17 AM p ~ d [ ] j \ p Ž ] ~ ~ [ ] j 9 The data member, pointee, is delared in the private setion at line 17. The onstrutor for the Pointer lass requires an initial value for pointee (whih defaults to U if omitted); this is shown at line 7. Classes that enapsulate the behavior of a pointer are sometimes alled smart pointer lasses. This lass is smarter than a plain pointer beause it automatially initializes itself to U, if no initial value is provided. mplementing operator< is idential to the PtrToShape lass in Setion As was done there, we just apply the < operator to the Comparable objets that are being pointed at. ote arefully that this is not irular logi. The (template) operator< at line 9 in lass Pointer ompares two Pointer types; the all at line 10 will ompare two Comparable types. ine 11 shows bizarre C++ syntax at its finest. This is the type onversion operator; in partiular, this method defines a type onversion from Pointer<Comparable> to Comparable *. The implementation is simple enough; we just return pointee at line 12. This allows us to get at the pointer. Although we ould have used a named member funtion, suh as get, at line 13, this type onversion simplifies the largebjetsort algorithm in Figure 9.9. t is important to remark that these type onversions are great when they work, but they an ause unexpeted problems. Consider the ode in Figure 5.8. We have provided operator!=, and to avoid any suspiious ompiler bugs, we write it as a real funtion, instead of a funtion template. Suppose that the onstrutor at line 7 in Figure 5.7 was not delared using expliit. n this ase line 13 would not ompile! This is beause an ambiguity would be reated. We an either onvert q to an int *, and use the!= operator that is defined for primitive pointer variables, or we an promote p to a Pointer<int>, using the onstrutor, and then use the!= defined for Pointer<int>. G G G G G // Define!= for two Pointer<int> objets. bool operator!= ( onst Pointer<int> & lhs, onst Pointer<int> & rhs ) return lhs < rhs rhs < lhs; int main( ) int *p = new int( 3 ); Pointer<int> q( new int( 4 ) ); Q RS T U V W X ¹ if( q!= p ) // Compare pointed-at objets??? out << "q and p are different" << endl; return 0; f ^ b q ^d h ^d e p q aƒ p ^ ] [ _ d ^ \ d ~ [ _ [ ] j ^ \ j +' " "! " -. ' -! 1 # ' ( * " / +' -! -.! &!. ' 0 %) $ ) 2 ' ( ) %1 -! $ ' $! # ' + +! Š 8 6 (! # ) 1 0! $ " %) 1 " # ' 1 # ' / "! / 1! 7 * (! # -! ( $ ) & +!, " 8 0 ) % / ' +* %$! # * - % ) 1 %, ( +%# % - # ) 1 0! $ * " %) 1 " %1 ' ) 1 * - $ %0 * %' + # +' " " 8

10 Patterns.mkr Page 232 Wednesday, August 25, :17 AM 9 9 There are lots of ways out of this quandary, but suffie it to say, beause of this, you should generally avoid dual-diretion impliit onversions in any nontrivial lass. f you always use expliit, or you never use type onversion operators, you won t have this problem. º» «¼ ½ «±.! auto_ptr 3 $ ' ( " ' ( ) % 1 -! $ ' 1 %- "! " - $ / # - ) $ # ' + +" delete 8 ¾ #! 1 ' $ % ) À Á Â! 1!! - ) +) # ' ', %# ' ++6 ' + +) # ' -! ) &! # - 8 delete ' The reently adopted C++ standard has added a new wrapper lass alled the auto_ptr. This lass is intended to help solve three ommon C++ pointer problems. Reall that if an objet is dynamially alloated by a all to new, then it must eventually be freed by a all to delete. therwise, we an have a memory (or other resoure) leak. The auto_ptr is intended to help do this automatially by wrapping the pointer inside the auto_ptr lass, and then having the auto_ptr destrutor all delete. There are three senarios that the auto_ptr is designed for. n the first senario, inside a funtion, a loal pointer variable alloates, via new, an objet that has loal sope only. When the funtion returns, it is expeted that the objet is freed by a all to delete. Typial ode looks like: void fun( ) bjet *obj = new bjet(... );... delete obj; ¾ #! 1 ' $ % ) à Á Â! 1!! - ) delete ' 1 ) &! # - # $! ' -! ' 1 $! - / $ 1! 2 $ ), ' # ), ( +! -! 2 / 1 # * - % ) 1 # ' ++ 8 This ode seems simple enough, but there are dangers lurking. f fun has multiple returns, then we must be areful that delete is always reahed. And if fun throws an unaught exeption, the delete never ours. owever, sine destrutors are always alled when a funtion exits (even if via an unaught exeption), if the pointer is wrapped inside an objet whose destrutor alls delete, the memory will be relaimed. The seond senario is a funtion that alloates an objet and returns a pointer to it. The aller is now expeted to all delete when it no longer needs the objet. Typial ode looks like: bjet *fun1( ) bjet *obj1 = new bjet(... );... return obj1;

11 Patterns.mkr Page 233 Wednesday, August 25, :17 AM p ~ d [ ] j \ p Ž ] ~ ~ [ ] j 9 void fun( ) bjet *obj = fun1( );... delete obj; This has similar problems as the first senario (we must make sure that we reah the delete in all ases), exept that we must make sure delete is not alled in fun1. A third senario is a funtion that alloates an objet and then alls another funtion, with the expetation that the other funtion will lean up, as shown below: void fun( bjet *obj )... delete obj; void fun1( ) bjet *obj1 = new bjet(... );... fun( obj1 );... We remark that this all the auto_ptr is expeted to be used for. Fanier automati garbage olletion requires more sophistiated logi. The basi property of the auto_ptr wrapper is as follows. t will wrap the pointer variable (thus it stores the value of the pointer as the pointee data member). t will also maintain an indiation of whether or not it is the owner of the pointer (as a Boolean iswner). f it is the owner, then when its destrutor is alled, it must apply the delete operator to the pointer. When a opy is performed ownership is transferred. Figure 5.9 illustrates our version, the AutoPointer. The basi onstrutor is shown starting at line 7. t simply sets pointee and iswner. The destrutor alls the member funtion free, whih itself alls delete if the AutoPointer is the owner (of pointee). ines 37 and 38 implement some of the same logi that was seen in the Pointer lass earlier in this setion. The ode in lines 33 to 36 implements the dereferening operator (whih is the equivalent of *pointee), and -> (whih is the equivalent of pointee). nly three other methods are left: release, the opy onstrutor, and operator=. The release method (lines 39 and 40) gives up ownership, but otherwise behaves like get. The intent is that it an be alled when ontrol is transferred by a opy operation. ¾ #! 1 ' $ %) Ä Á Â! 1!! - ) delete 6 1 ', %# ' ++6 ' ++) * ' # ' -! ) &! # - # $! * ' -! & 6 -.! # ' ++% / 1 # - %) 1 8 Å ) 1 ) - / "! auto_ptr, ) $! -. ' 1 %" 2 % ) 1 $ * -! 1! 8.!! " - $ / # - ) $ # ' ++" %2 %- ) 3 1 " delete -.! ( ) %1 -!! 8.! release,! -. ) 4 %0! " / ( ) 3 1! $ ". % ( ) 2 -.! ( ) %1 -!! 8

12 M G Patterns.mkr Page 234 Wednesday, August 25, :17 AM 9 : G G G G G G M G P G M P G M P G M // Class that wraps a loal pointer variable. template <lass bjet> lass AutoPointer publi: expliit AutoPointer( bjet *rhs = U ) : iswner( rhs!= U ), pointee( rhs ) ; AutoPointer( AutoPointer & rhs ) : iswner( rhs.iswner ) pointee = rhs.release( ); ~AutoPointer( ) free( ); onst AutoPointer & operator= ( AutoPointer & rhs ) if( this!= & rhs ) bjet *other = rhs.get( ); if( other!= pointee ) free( ); pointee = other; else if( rhs.iswner ) iswner = true; pointee = rhs.release( ); return *this; bjet & operator* ( ) onst return *get( ); bjet * operator-> ( ) onst return get( ); bjet * get( ) onst return pointee; bjet * release( ) iswner = false; return pointee; private: bjet *pointee; bool iswner; Q RS T U V W X Æ r e [ void free( ) if( iswner ) delete pointee; auto_ptr _ a j j t h [ q j [ p ^ [ ] [ \ d \ l l f [ v

13 Ç Patterns.mkr Page 235 Wednesday, August 25, :17 AM p ~ d [ ] j \ p Ž ] ~ ~ [ ] j 9 w Thus, in the opy onstrutor at lines 10 and 11, instead of opying the pointer value with pointee=rhs.pointee, rhs.pointee.release() is used on the right-hand side. wnership is transferred via the initializer list. The most ompliated routine is the opy assignment operator, shown at lines 16 to 31. The main ompliation is that before opying into the target, we must all delete on the target s urrent pointee if the target owns it (and the target s urrent pointee is different than the new pointee). The main differene between this implementation and the implementation in the C++ standard is behavior under inheritane. Speifially, onsider lasses Base and Derived, as usual. Although a Derived* value an be opied into a Base* value, an AutoPointer<Derived> objet annot be opied into a AutoPointer<Base> objet in our implementation. Adding this funtionality requires using member templates. Member templates allow us to delare member funtion templates, using additional template types. For instane, here is how the opy onstrutor would look: template<lass therbjet> AutoPointer( AutoPointer<therbjet> & rhs ) : iswner( rhs.iswner ) pointee = rhs.release( ); n this senario, we define the onstrution (no longer a opy onstrutor) of an AutoPointer of one type with an AutoPointer of any other type. owever, the assignment statement will generate a ompiler error if the underlying pointees are not type ompatible. While this is a slik solution, unfortunately, member templates are a reent language addition that is not supported on all ompilers. š œ Ê Ë Ì Í Ÿ Î ž Ÿ Ÿ Referene variables in C++ are different from pointer variables in several ways. ne important differene is that whereas pointer variables an point at either an objet or U, a referene variable must referene an objet. Sometimes this is unfortunate. For instane, when we searh for an objet in an arbitrary ontainer, we may want to return a referene to it. But what if the objet is not found? The solution, as usual, is to wrap the behavior of a referene variable inside a lass. ur lass, Cref, shown in Figure 5.10, mimis a onstant referene variable. (Alternatively, we ould implement a simple referene lass, and even use inheritane to make the referene and onstant referene lasses type ompatible. This is left as Exerise 5.18.) The implementation is straightforward. We store a pointer to the referened objet as a private data member. The pointer is initialized in the onstrutor, but is U if Cref is onstruted with no parameters. We provide a get method that returns the onstant referene and an isull method that returns true if the null referene is being represented. È ' + +) 3 / " - )! # +' $!,!, &! $ 2 / 1 # - %) 1 -!, ( +' -! " 5 / " %1 4 ' %- %) 1 ' + -!, * ( + ' -! - 6 (! " 8.!, ' %1 %2 2! $ *! 1 #! &! - 3!! 1 -. % " %, ( +!,! 1 - ' - %) 1 ' 1 -.! %, ( +!, É É! 1 * - ' - % ) 1 %1 -.! " - ' 1 ' $ %" &!. ' 0 * %) $ / 1! $ %1.! $ %* - ' 1 #! 8 $! 2! $! 1 #! 0 ' $ %* ' & +!, / " - $! 2! $ *! 1 #! ' 1 ) &! # - 8 ¾ ),! - %,! " -. %" %" / 1 * 2 ) $ - / 1 ' -! 8 Cref. ' 0 %) $ 3 ) $ 2 ' ' ( $ "! - 2.!! $ * &! *! 1 #! 0 ' $ %' & +! %1 " %! ' # +' " " 8 Cref ( $ ) 0 %! " ' 1 isull -. ' - $! - / $ 1, "! - $ - /.! ) %2 -.! 1 / ++ $! 2! $! 1 #! %" &! %1 4 $! ( $! "! 1 -! 8

14 M G l Patterns.mkr Page 236 Wednesday, August 25, :17 AM 9 z G G G G G G M G P G // Class that wraps a onstant referene variable. // Useful for return value from a ontainer find method. template <lass bjet> lass Cref publi: Cref( ) : obj( U ) expliit Cref( onst bjet & x ) : obj( &x ) onst bjet & get( ) onst if( isull( ) ) throw ullpointerexeption( ); else return *obj; bool isull( ) onst return obj == U; private: onst bjet *obj; ; Q RS T U V W X Y Ï \ j d \ d ] [ [ ] [ \ _ [ h ] ~ ~ [ ] š œ œ Ë Ð Ÿ Ñ Ì Ò Ó Ó Ô Ÿ Î.! ' ' ( -! $ ( ' - * -! $ 1 %" / "! - ) #. ' 1 4! -.! %1 -! $ * 2 ' #! ) 2 ' 1! 7 %" - %1 4 # +' " " - ) # ) 1 2 ) $, - ) ' 1 ) -.! $ 8 The adapter pattern is used to hange the interfae of an existing lass to onform to another. Sometimes it is used to provide a simpler interfae, either with fewer methods, or easier-to-use methods. ther times it is used simply to hange some method names. n either ase, the implementation tehnique is similar. As an example, our MemoryCell lass in Setion 3.4 uses read and write. But what if we wanted the interfae to use get and put instead? There are two reasonable alternatives. ne is to use omposition. owever, this means, for instane, that a all to get will then all read, thus adding an extra layer of overhead. The other alternative is to use private inheritane. We use private inheritane to implement the new lass, StorageCell, in Figure ts methods are implemented by alls to the base lass methods. As disussed in Setion 4.4.5, in private inheritane, publi methods in the base lass are private in the derived lass. Thus, as Figure 5.12 illustrates, the only visible methods are the StorageCell onstrutor, get, and put.

15 M G M Õ p \ \ b y [ \ b d Patterns.mkr Page 237 Wednesday, August 25, :17 AM G G G G // A lass for simulating a memory ell. template <lass bjet> lass StorageCell : private MemoryCell<bjet> publi: expliit StorageCell( onst bjet & initialvalue = bjet( ) ) : MemoryCell<bjet>( initialvalue ) onst bjet & get( ) onst return read( ); void put( onst bjet & x ) write( x ); ; Q RS T U V W X Y Y \ q j [ ~ d [ ] _ \ p get j j d e a put d _ e [ j d e [ MemoryCell ^ \ d [ ] _ [ d l Õd [ ] ] j 9 G G int main( ) StorageCell<int> m1; StorageCell<string> m2( "hello" ); m1.put( 37 ); m2.put( m2.get( ) + " world" ); out << m1.get( ) << endl << m2.get( ) << endl; // The next line does not ompile if unommented. // out << m1.read( ) << endl; return 0; Q RS T U V W X Y x q j d ] d ^ a a ] [ \ a ~ ] ^ d [ ^ \ e [ ] ^d [ l ] y ^j ^ m a \ _ [ g d e [ MemoryCell f [ d e p j Consider the problem of printing the elements in a olletion. Typially, the olletion is an array, so assuming that the objet v is an expanded vetor template, its ontents are easily printed with ode like: 1 Š ) &! # - # ) 1 - $ ) + " %-! $ ' - %) 1 ) 2 ' # ) ++! # - %) 1 8 for( int i = 0; i < v.size( ); i++ ) out << v[ i ] << endl;

16 Patterns.mkr Page 238 Wednesday, August 25, :17 AM 9 Œ Â.! 1 3! ( $ ) 4 $ ', - ) ' 1 %1 -! $ 2 ' #! 5 3! 3 $ %-! # )! -. ' - / "! " -.!, ) " - ' & " - $ ' # -,! -. ) " 8.! "!,! -. ) " 3 %++ &! ' ( * ( +%! - ) -.! ' # - / ' + # ) 1 # $! -! - 6 (! " 8 n this loop, i is an iterator objet, beause it is the objet that is used to ontrol the iteration. owever, using the integer i as an iterator onstrains the design: We an only store the olletion in an array-like struture. A more flexible alternative is to design an iterator lass that enapsulates a position inside of a olletion. The iterator lass provides methods to step through the olletion. The key is the onept of programming to an interfae: We want the ode that performs aess of the ontainer to be as independent of the type of the ontainer as possible. This is done by using only methods that are ommon to all ontainers and their iterators. There are many different possible iterator designs. We desribe three designs, in inreasing order of omplexity. terators are a ore omponent of the ST, and its design is similar to our seond design (but of ourse, is slightly more omplex). n Chapter 7, we disuss ST iterators. They are used throughout the ase studies in Part and some implementations of these iterators and the olletions that they iterate over are provided in Part V. š Ô Ÿ Ÿ Ø Ó Ù getterator $! * - / $ 1 " ' 1 ' ( ( $ ) ( $ %* ' -! %-! $ ' - ) $ 2 ) $ -.! # ) ++! # - %) 1 8 The first iterator design uses only three methods. The ontainer lass is required to provide a getterator method. getterator returns an appropriate iterator for the olletion. The iterator lass has the other two methods, hasext and next. hasext returns true if the iteration has not yet been exhausted. next returns the next item in the olletion (and in the proess, advanes the notion of the urrent position). This iterator interfae mathes one that is provided in the ava programming language. To illustrate the implementation of this design, we write the olletion and iterator lass templates, MyVetor and Vetorterator, respetively. Their use is shown in Figure MyVetor is written in Figure To simplify matters, we inherit from the vetor lass. The only differene between MyVetor and vetor is its getterator method. (The use of inheritane here has nothing to do with the iterator pattern.)

17 M G M d d Patterns.mkr Page 239 Wednesday, August 25, :17 AM G G G G int main( ) MyVetor<int> v; Q RS T U V W X Y v.push_bak( 3 ); v.push_bak( 2 ); out << "Vetor ontents: " << endl; Vetorterator<int> itr = v.getterator( ); while( itr.hasext( ) ) out << itr.next( ) << endl; return 0; main f [ d e p d ^ q j d ] a a d [ ^d [ ] ] p [ j ^ b \ Ú Û Õd [ ] ] j 9 G G G G G G M template <lass bjet> lass Vetorterator; // Same as the vetor, but has a getterator method. // o extra data, no overridden methods, so non-virtual // destrutor in original vetor is! template <lass bjet> lass MyVetor : publi vetor<bjet> publi: expliit MyVetor( int size = 0 ) : vetor<bjet>( size ) ; Q RS T U V W X Y r e [ Vetorterator<bjet> getterator( ) onst return Vetorterator<bjet>( this ); MyVetor _ a j j o p [ j ^ b \ j Ú Û \ p Ú Ü

18 M G \ Patterns.mkr Page 240 Wednesday, August 25, :17 AM 9 : G G G G G G M G // A passive iterator lass. Steps through its MyVetor. template <lass bjet> lass Vetorterator publi: Vetorterator( onst MyVetor<bjet> *v ) : owner( v ), ount( 0 ) bool hasext( ) onst return ount!= owner->size( ); onst bjet & next( ) return (*owner)[ ount++ ]; private: onst MyVetor<bjet> *owner; int ount; ; Q RS T U V W X Y W Õ f ~ [ f [ \ d a d ^ l d e [ Vetorterator o p [ j ^b \ Ú Û.! % -! $ ' - ) $ %" # ) 1 * " - $ / # -! 3 %-. ' ( ) %1 -! $ - ) -.! # ) 1 * - ' %1! $ -. ' - % - %-! $ * ' -! " ) 0! $ 8 getterator simply returns a new iterator; notie that the iterator must have information about the ontainer that it is iterating over. Thus the iterator is onstruted with a pointer to the vetor. The only other method in MyVetor is the onstrutor, whih simply alls the base-lass onstrutor. Beause we are using publi inheritane, it would be proper to hange the vetor lass destrutor to be virtual, if possible. owever, in this ase it does not matter, sine MyVetor adds no extra data members. As a result, this turns out to be a nie example of publi inheritane.

19 M G ] f \ \ o d Patterns.mkr Page 241 Wednesday, August 25, :17 AM G G G G G G M G P G M P G M P G // A passive iterator lass. Steps through its MyVetor. template <lass bjet> lass Vetorterator publi: Vetorterator( onst MyVetor<bjet> *v ) : owner( v ), ount( 0 ) void reset( ) ount = 0; bool isvalid( ) onst return ount < owner->size( ); void advane( ) ount++; onst bjet & retrieve( ) onst return (*owner)[ ount ]; private: onst MyVetor<bjet> *owner; int ount; ; int main( ) MyVetor<int> v; v.push_bak( 3 ); v.push_bak( 2 ); Vetorterator<int> itr = v.getterator( ); for( int i = 0; i < 2; i++ ) out << "Vetor ontents: " << endl; for( itr.reset( ); itr.isvalid( ); itr.advane( ) ) out << itr.retrieve( ) << endl; return 0; Q RS T U V W X Y \ [ h \ p Vetorterator d [ j d ~ ] o h ^d e j b f [ p p ^d ^ a l q \ _ d ^ ^d a k Õd [ ] ] j 9 :

20 Patterns.mkr Page 242 Wednesday, August 25, :17 AM 9 : 9 Ý1 # ), ( +! -! # + ' " "! # +' $ ' - %) 1 " ' $! 1! #! " " ' $ 6 3.! 1-3 ) ) $, ) $! # +' " "! " $! 2! $ - )! ' #. # %$ # / * +' $ +6 8 ines 1 and 2 represent an inomplete lass delaration. This partiular delaration states that Vetorterator is a lass template, but does not provide the lass definition. owever, this is enough to make line 16 ompile. nomplete lass delarations are neessary when two or more lasses refer to eah irularly. Figure 5.15 shows the Vetorterator. The iterator keeps a variable (ount) that represents the urrent position in the vetor, and a pointer to the vetor. The implementation of the onstrutor and two member funtions is straightforward. The onstrutor diretly initializes the data members in the initializer list, hasext simply ompares the urrent position with the vetor size, and next uses the urrent position to index the array (and then advanes the urrent position). otie the use of onst throughout, to ensure that this iterator makes no attempt to modify the ontainer. š Ê Ô Ÿ Ÿ Ø Ó Ù Ê.! "! # ) 1! " %4 1 ( / - ", ) $! 2 / 1 # - % ) 1 * ' + %- 6 %1 -.! %-! $ ' - ) $.! ¾ Þ %-! $ ' - ) $. ' " " ),! # ),, ) 1 ' +%- 6 3 %-. ) / $ "! # ) 1! * " %4 1 5 & / - ' +" ) " ),! %, ( ) $ - ' 1 - %2 2! $ *! 1 #! " 8 A limitation of the first iterator design is the relatively limited interfae. bserve that it is impossible to reset the iterator bak to the beginning, and that the next method ouples aess of an item with advaning. A seond design, shown in Figure 5.16, puts more funtionality in the iterator. t leaves the MyVetor lass ompletely unhanged. The ST iterator has some ommonality with our seond design, but also some important differenes. t is similar in that the methods to advane and retrieve are separate. t is different in that the iterator an make hanges to the underlying olletion.

21 M G ~ d ] d d Patterns.mkr Page 243 Wednesday, August 25, :17 AM G G G G G G M G P template <lass bjet> lass terator; template <lass bjet> lass Vetorterator; // Same as the vetor, but has a getterator method. // o extra data, no overridden methods, so non-virtual // destrutor in original vetor is! template <lass bjet> lass MyVetor : publi vetor<bjet> publi: expliit MyVetor( int size = 0 ) : vetor<bjet>( size ) ; Q RS T U V W X Y µ terator<bjet> *getterator( ) onst return new Vetorterator<bjet>( this ); Õ \ e [ ] ^d \ _ [ j [ p ^d [ ] ^ \ d [ ] d ƒ \ m ^d [ ] ] p [ j ^ b \ getterator ] [ d q ] \ j Õd [ ] ] j 9 :

22 M G d ] _ \ Patterns.mkr Page 244 Wednesday, August 25, :17 AM 9 : : G G G G G G M G P G M P G // A passive iterator lass protool. // Steps through its ontainer. template <lass bjet> lass terator publi: virtual ~terator( ) ; virtual bool hasext( ) onst = 0; virtual onst bjet & next( ) = 0; // A onrete implementation of the iterator. // Could have been nested inside of MyVetor! template <lass bjet> lass Vetorterator : publi terator<bjet> publi: Vetorterator( onst MyVetor<bjet> *v ) : owner( v ), ount( 0 ) bool hasext( ) onst return ount!= owner->size( ); onst bjet & next( ) return (*owner)[ ount++ ]; private: onst MyVetor<bjet> *owner; int ount; ; Q RS T U V W X Y ¹ r e [ ^d [ ] m j d ] _ d _ a j j \ p \ _ ] [ d [ ^ f ~ [ f [ \ d a d ^ Another differene is that the ST iterator does not have isvalid or reset methods. nstead, the ontainer has a method to return an invalid iterator and a method to return an iterator representing the starting point. We an test if an iterator is in an invalid state by omparing it with the invalid iterator given by the ontainer. We an reset the iterator by opying the starting point iterator into it. The ST also makes extensive use of operator overloading. For example, advane is replaed with operator++. Details on using ST iterators an be found in Chapter 7.

23 d Patterns.mkr Page 245 Wednesday, August 25, :17 AM š œ Ô Ò Ÿ Î ß à Ð Ô Ÿ Ÿ Ð á Î Ÿ Õd [ ] ] j 9 : w The iterators designed so far manage to abstrat the onept of iteration into an iterator lass. This is good, beause it means that if the olletion hanges from an array-based olletion to something else, the basi ode suh as lines 38 and 39 in Figure 5.16 does not need to hange. While this is a signifiant improvement, hanges from an array-based olletion to something else require that we hange all the delarations of the iterator. For instane, in Figure 5.16, we would need to hange line 33. We disuss an alternative in this setion. ur basi idea is to define an abstrat base lass terator. Corresponding to eah different kind of ontain is an iterator that implements the terator protool. n our example, this gives three lasses: MyVetor, terator, and Vetorterator. The relationship that holds is Vetorterator S-A terator. The reason we do this is that eah ontainer an now reate an appropriate iterator, but pass it bak as an abstrat terator. Figure 5.17 shows MyVetor. The new MyVetor returns a pointer to an terator objet that is dynamially onstruted by alling new. Sine Vetorterator S-A terator, this is safe to do. otie that the use of inheritane and polymorphism will require that we introdue pointers or referenes. As we will see, this muddies the ode a bit, whih is one reason why the ST is template-based, rather than inheritane-based. Beause getterator reates and returns a new terator objet, whose atual type is unknown, it is ommonly known as a fatory method. The iterator lasses are shown in Figure First, we have the abstrat lass terator, whih serves simply to establish the protool by whih all sublasses of terator an be aessed. The protool is speified with pure virtual funtions. As usual, we have a virtual destrutor. This version of Vetorterator is essentially idential to the original implementation in Figure 5.18, exept that it is a derived lass of terator. 1 % 1.! $ %- ' 1 #! * & ' "! %-! $ ' - %) 1 " #.!,!! 2 %1! " ' 1 %-! $ ' - ) $ ' & " - $ ' # - & ' "! # +' " " 8 +%! 1 - " ( $ ) 4 $ ', - ) -. % " %1 * -! $ 2 ' #! 8.! %1.! $ %- ' 1 #! * & ' "! " #.!,! %1 * - $ ) / #! " ( ) %1 -! $ " â ) $ $! 2! $! 1 #! " ã 8.! %-! $ ' - ) $ " ' $! 1 ) 3 ' +* +) # ' -! & 6 new 8 ä Š å æ Š # $! ' -! " ' 1! 3 # ) 1 * # $! -! %1 " - ' 1 #! 5 & / - $! - / $ 1 " %- / " %1 4 ' ( ) %1 -! $ â ) $ $! 2! $ *! 1 #! ã - ) -.! ' & * " - $ ' # - # +' " " 8

24 M \ d \ Patterns.mkr Page 246 Wednesday, August 25, :17 AM 9 : z int main( ) MyVetor<int> v; v.push_bak( 3 ); v.push_bak( 2 ); G G G G G G M Q RS T U V W X Y Æ out << "Vetor ontents: " << endl; terator<int> *itr = v.getterator( ); while( itr->hasext( ) ) out << itr->next( ) << endl; delete itr; return 0; Õ q j d ] a a d ^ l d e [ q j [ l ^d [ ] ] j ^ \ ^ \ e [ ] ^d \ _ [ ƒ m j [ p p [ j ^ b ç ) 3.! $! %1 -.! $! ' 1 6,! 1 - % ) 1 ) 2 -.! ' # - / ' + %-! $ ' * - ) $ - 6 (! 8 main %".! 6 1 ', % # ' + +6 ' +* +) # ' -! % -! $ ' - ) $, / " - &! $! # + ' %,! & 6 # ' ++%1 4 delete 8 Figure 5.19 demonstrates how the inheritane-based iterators are used. At line 10, we see the delaration of itr: it is now a pointer to an terator. owhere in main is there any mention of the atual Vetorterator type. n fat, we ould have written Vetorterator as a nested lass in the private setion of MyVetor. The fat that a Vetorterator exists is not used by any lients of the MyVetor lass. This is a very slik design, and illustrates niely the idea of hiding an implementation and programming to an interfae. The hanges to main are relatively minimal. ines 11 and 12 hange beause we must use operator-> instead of the dot operator. ine 14 illustrates a down side: the dynamially alloated iterator must be relaimed by alling delete. Remembering to do this all the time is annoying. owever, if we examine this losely, we see a lassi appliation of senario #2 for the auto_ptr. Reall from Setion (page232) that in this senario, an objet is alloated inside a funtion (in this ase, getterator), and is returned to the aller. The aller is responsible for handling the delete. This is exatly the situation in Figure Thus although inonvenient, there is some support in the language to make our life easier. By the way, reall that at the end of Setion (beginning on page 235), we explained that our version of AutoPointer differed from the ST auto_ptr beause the ST version allows any ompatible pointers to be wrapped, while our version requires an exat type math. We also explained that member templates ould be used to loosen the requirement of an exat type math. f we look at how the auto_ptr would be used here, we see that we would need to do the following:

25 ë Patterns.mkr Page 247 Wednesday, August 25, :17 AM f ~ j ^d [ t è ^ ] v 9 : 1. n Figure 5.19, line 10, itr would be an auto_ptr, and line 14 would disappear. 2. n Figure 5.17, getterator would be rewritten to return an auto_ptr (line 18) and the result of new would be wrapped inside an auto_ptr (line 19). These hanges to getterator, give the following implementation: auto_ptr<terator<bjet> > getterator( ) onst return auto_ptr<terator<bjet> >( new Vetorterator<bjet>( this ) ); The onstrution of an auto_ptr<terator<bjet> >, with a Vetorterator<bjet> pointer, implies that we need the ST version. B A B F n most languages, a funtion an return only a single objet. What do we do if we need to return two or more things? There are several possibilities. ne alternative is to use referene variables. The other is to ombine the objets into a single strut (or lass). The most ommon situation in whih multiple objets need to be returned is the ase of two objets. So a ommon design pattern is to return the two objets as a pair. This is the Composite pattern. n addition to the situation desribed above, pairs are useful for implementing maps and ditionaries. n both these abstrations, we maintain key-value pairs: the pairs are added into the map or ditionary, and then we searh for a key, returning its value. ne ommon way to implement a map as to use a set. n a set, we have a olletion of items, and searh for a math. f the items are pairs, and the math riterion is based exlusively on the key omponent of the pair, then it is easy to write an adapter lass that onstruts a map on the basis of a set. We will see this idea explored in more detail in Chapter 19. The Standard Template ibrary defines a pair lass. An implementation is shown in Figure otie that it is a lass only in the tehnial sense; the data members are publi. # ),, ) 1! " %4 1 ( ' - -! $ 1 % " - ) $! - / $ 1-3 ) ) &! # - " ' " ' 8 ' %$ " ' $! / "! 2 / + 2 ) $ %, ( +!,! 1 - %1 4 ì! 6 * 0 ' + /! ( ' %$ " %1, ' ( " ' 1 %# - %) 1 ' $ %! " 8.! ¾ Þ! 2 %1! " ' pair # +' " " 8

26 ˆ G M y \ Patterns.mkr Page 248 Wednesday, August 25, :17 AM 9 : Œ í C D î.! ï & "! $ 0! $ ( ' - * -! $ 1 %1 0 ) + 0! " ' È ð ñ ' 1 ' "! - ) 2 Š È ò 8.! ) & * "! $ 0! $ " ' $! - ) &! %1 * 2 ) $,! 3.! 1! 0! $ " ),! -. % 1 4 % 1 -! $! " - * %1 4. ' ( (! 1 " - ) -.! " / &! # - 8 ur last pattern is the bserver pattern. The typial use of the bserver pattern involves a subjet and a set of observers. For this to be interesting, the number of observers an vary as the appliation runs, and an be large. The basi premise is that the observers are to be informed whenever something interesting happens to the subjet. A simplisti example of this ould be a windowing operating system, suh as Windows or Ma /S. When a window is reated or maximized, it overs other windows. These windows that are overed are now observers in the sense that they want to be informed when the newly reated window is minimized or destroyed, or simply moved, as this might require that the previously hidden windows be redrawn. G G // Class (more like a strut) that stores // a pair of objets. template <lass Type1, lass Type2> lass pair publi: Type1 first; Type2 seond; pair( onst Type1 & f = Type1( ), onst Type2 & s = Type2( ) ) : first( f ), seond( s ) ; Q RS T U V W X x Ï r e [ pair _ j j ó j ^_ d e [ j a m a ak f [ j d e [ r ô [ ] j ^ Another example might be a lass that wraps pointers. Several wrapper objets may be sharing a pointee that is pointing at some dynamially alloated objet. f one instane of the wrapper alls delete on the dynamially alloated objet, then the other wrappers have stale pointers, whih gives undefined behavior that an be hard to detet. A solution is that when the delete is performed, we inform all the wrappers that are looking at that deleted objet, perhaps setting their pointees to U to insure defined behavior. Figure 5.21 ontains an abstrat base lass bserver and base lass (whih ould be abstrat, but is not) for Subjet.

27 M G m ] ] m Patterns.mkr Page 249 Wednesday, August 25, :17 AM The bserver abstrat lass speifies a protool: when something interesting happens, the bserver is told about it by having its update method alled. A sublass an override update to handle the interesting ourrene. For instane, in our windowing example, the observer windows will have their update method alled when the window that was overing it is no longer in the way. The update method ould redraw an appropriate portion of the sreen. G G G G G G M G P G M P lass Subjet; lass bserver publi: virtual ~bserver( ) virtual void update( Subjet *observee ) = 0; ; lass Subjet publi: virtual ~Subjet( ) // Add obs to the set of observers; see online ode. virtual void addbserver( bserver *obs ); // Remove obs from the set of observers. virtual void removebserver( bserver *obs ); // Call the update method for all observers. virtual void notifyall( ) for( int i = 0; i < observers.size( ); i++ ) observers[ i ]->update( this ); private: vetor<bserver *> observers; ; Q RS T U V W X x Y j d ] _ d _ j j [ j t a l Subjet v bserver o \ p m j [ _ a j j l m j [ ] y [ [ u j [ ] y [ ] 9 :.! bserver " - $ ' # - # +' " " " (! # %* ' & * 2 %! " ' ( $ ) - ) # ) + Á 3.! 1 " ),! -. %1 4 %1 * -! $! " - %1 4. ' ( (! 1 " 5 -.! bserver - ) + ' & ) / - %- & 6 %". ' 0 %1 4 %- " update,! -. ) # ' + +! 8 The Subjet lass is not abstrat (but see Exerise 5.7). nstead it defines methods to add an observer, remove an observer, and notify all observers that something has happened. t does this by keeping an internal list of all registered observers (possibly in a vetor). The implementation of addbserver and removebserver an be found in the online ode. An illustration of the bserver pattern in ation is shown in Figure ere we have a subjet, whih is a Timer objet, and we have Eho objets whih.! Subjet! 2 %1! ",! -. ) # " +' - ) " " ' ' 1 ) & "! $ 0! $ 5 $!, ) 0! ' 1 ) & * "! $ 0! $ 5 ' 1 1 ) - % 2 6 ' + + ) & "! $ 0! $ " -. ' - " ),! -. % 1 4. ' ". ' ( * (! 1!

28 M G j y Patterns.mkr Page 250 Wednesday, August 25, :17 AM 9 w are the interested observers. The Timer objet has a tik method; whenever the tik method is alled, any Eho objets that are observing the Timer objet are notified, and their update method is alled. n our example, the update method simply prints a message, so we an see that the notifiation ourred. G G G G G G M G P G M P G // Timer lass: tik method alls notify lass Timer : publi Subjet publi: void tik( ) notifyall( ); ; // Eho lass: this in an observer. // t is onstruted with a Timer objet; when // the Timer objet tiks, update is // automatially alled. lass Eho : publi bserver publi: Eho( int id, Timer *t ) : myd( id ), observee( t ) observee->addbserver( this ); ~Eho( ) observee->removebserver( this ); void update( Subjet *s ) if( observee == s ) out << myd << endl; private: int myd; Subjet *observee; ; Q RS T U V W X x x \ _ ] [ d [ _ j j [ j g j [ ] [ j [ _ d o a Eho m Timer h e [ \ d e [ m n Timerõ tik f [ d e p ^j _ [ p a a \ p ] [ _ d j

Chapter 2: Introduction to Maple V

Chapter 2: Introduction to Maple V Chapter 2: Introdution to Maple V 2-1 Working with Maple Worksheets Try It! (p. 15) Start a Maple session with an empty worksheet. The name of the worksheet should be Untitled (1). Use one of the standard

More information

Outline: Software Design

Outline: Software Design Outline: Software Design. Goals History of software design ideas Design priniples Design methods Life belt or leg iron? (Budgen) Copyright Nany Leveson, Sept. 1999 A Little History... At first, struggling

More information

O Type of array element

O Type of array element ! " #! $ % % # & : ; a ontiguous sequene of variables. all of the sae type. Eah variable is identified by its index. Index values are integers. Index of first entry is. ' ( ) * + May /,. - ( & ( ( J K

More information

Learning Convention Propagation in BeerAdvocate Reviews from a etwork Perspective. Abstract

Learning Convention Propagation in BeerAdvocate Reviews from a etwork Perspective. Abstract CS 9 Projet Final Report: Learning Convention Propagation in BeerAdvoate Reviews from a etwork Perspetive Abstrat We look at the way onventions propagate between reviews on the BeerAdvoate dataset, and

More information

Exploring the Commonality in Feature Modeling Notations

Exploring the Commonality in Feature Modeling Notations Exploring the Commonality in Feature Modeling Notations Miloslav ŠÍPKA Slovak University of Tehnology Faulty of Informatis and Information Tehnologies Ilkovičova 3, 842 16 Bratislava, Slovakia miloslav.sipka@gmail.om

More information

Runtime Support for OOLs Part II Comp 412

Runtime Support for OOLs Part II Comp 412 COMP 412 FALL 2017 Runtime Support for OOLs Part II Comp 412 soure IR Front End Optimizer Bak End IR target Copright 2017, Keith D. Cooper & Linda Torzon, all rights reserved. Students enrolled in Comp

More information

Department of Electrical and Computer Engineering University of Wisconsin Madison. Fall

Department of Electrical and Computer Engineering University of Wisconsin Madison. Fall Department of Eletrial and Computer Engineering University of Wisonsin Madison ECE 553: Testing and Testable Design of Digital Systems Fall 2014-2015 Assignment #2 Date Tuesday, September 25, 2014 Due

More information

Reading Object Code. A Visible/Z Lesson

Reading Object Code. A Visible/Z Lesson Reading Objet Code A Visible/Z Lesson The Idea: When programming in a high-level language, we rarely have to think about the speifi ode that is generated for eah instrution by a ompiler. But as an assembly

More information

Divide-and-conquer algorithms 1

Divide-and-conquer algorithms 1 * 1 Multipliation Divide-and-onquer algorithms 1 The mathematiian Gauss one notied that although the produt of two omplex numbers seems to! involve four real-number multipliations it an in fat be done

More information

Analysis of input and output configurations for use in four-valued CCD programmable logic arrays

Analysis of input and output configurations for use in four-valued CCD programmable logic arrays nalysis of input and output onfigurations for use in four-valued D programmable logi arrays J.T. utler H.G. Kerkhoff ndexing terms: Logi, iruit theory and design, harge-oupled devies bstrat: s in binary,

More information

Run Time Environment. Implementing Object-Oriented Languages

Run Time Environment. Implementing Object-Oriented Languages Run Time Environment Implementing Objet-Oriented Languages Copright 2017, Pedro C. Diniz, all rights reserved. Students enrolled in the Compilers lass at the Universit of Southern California have epliit

More information

1. The collection of the vowels in the word probability. 2. The collection of real numbers that satisfy the equation x 9 = 0.

1. The collection of the vowels in the word probability. 2. The collection of real numbers that satisfy the equation x 9 = 0. C HPTER 1 SETS I. DEFINITION OF SET We begin our study of probability with the disussion of the basi onept of set. We assume that there is a ommon understanding of what is meant by the notion of a olletion

More information

Extracting Partition Statistics from Semistructured Data

Extracting Partition Statistics from Semistructured Data Extrating Partition Statistis from Semistrutured Data John N. Wilson Rihard Gourlay Robert Japp Mathias Neumüller Department of Computer and Information Sienes University of Strathlyde, Glasgow, UK {jnw,rsg,rpj,mathias}@is.strath.a.uk

More information

Algorithms for External Memory Lecture 6 Graph Algorithms - Weighted List Ranking

Algorithms for External Memory Lecture 6 Graph Algorithms - Weighted List Ranking Algorithms for External Memory Leture 6 Graph Algorithms - Weighted List Ranking Leturer: Nodari Sithinava Sribe: Andi Hellmund, Simon Ohsenreither 1 Introdution & Motivation After talking about I/O-effiient

More information

Reading Object Code. A Visible/Z Lesson

Reading Object Code. A Visible/Z Lesson Reading Objet Code A Visible/Z Lesson The Idea: When programming in a high-level language, we rarely have to think about the speifi ode that is generated for eah instrution by a ompiler. But as an assembly

More information

What are Cycle-Stealing Systems Good For? A Detailed Performance Model Case Study

What are Cycle-Stealing Systems Good For? A Detailed Performance Model Case Study What are Cyle-Stealing Systems Good For? A Detailed Performane Model Case Study Wayne Kelly and Jiro Sumitomo Queensland University of Tehnology, Australia {w.kelly, j.sumitomo}@qut.edu.au Abstrat The

More information

CleanUp: Improving Quadrilateral Finite Element Meshes

CleanUp: Improving Quadrilateral Finite Element Meshes CleanUp: Improving Quadrilateral Finite Element Meshes Paul Kinney MD-10 ECC P.O. Box 203 Ford Motor Company Dearborn, MI. 8121 (313) 28-1228 pkinney@ford.om Abstrat: Unless an all quadrilateral (quad)

More information

Contents Contents...I List of Tables...VIII List of Figures...IX 1. Introduction Information Retrieval... 8

Contents Contents...I List of Tables...VIII List of Figures...IX 1. Introduction Information Retrieval... 8 Contents Contents...I List of Tables...VIII List of Figures...IX 1. Introdution... 1 1.1. Internet Information...2 1.2. Internet Information Retrieval...3 1.2.1. Doument Indexing...4 1.2.2. Doument Retrieval...4

More information

1 The Knuth-Morris-Pratt Algorithm

1 The Knuth-Morris-Pratt Algorithm 5-45/65: Design & Analysis of Algorithms September 26, 26 Leture #9: String Mathing last hanged: September 26, 27 There s an entire field dediated to solving problems on strings. The book Algorithms on

More information

Algorithms, Mechanisms and Procedures for the Computer-aided Project Generation System

Algorithms, Mechanisms and Procedures for the Computer-aided Project Generation System Algorithms, Mehanisms and Proedures for the Computer-aided Projet Generation System Anton O. Butko 1*, Aleksandr P. Briukhovetskii 2, Dmitry E. Grigoriev 2# and Konstantin S. Kalashnikov 3 1 Department

More information

13.1 Numerical Evaluation of Integrals Over One Dimension

13.1 Numerical Evaluation of Integrals Over One Dimension 13.1 Numerial Evaluation of Integrals Over One Dimension A. Purpose This olletion of subprograms estimates the value of the integral b a f(x) dx where the integrand f(x) and the limits a and b are supplied

More information

OvidSP Quick Reference Card

OvidSP Quick Reference Card OvidSP Quik Referene Card Searh in any of several dynami modes, ombine results, apply limits, use improved researh tools, develop strategies, save searhes, set automati alerts and RSS feeds, share results...

More information

Automatic Physical Design Tuning: Workload as a Sequence Sanjay Agrawal Microsoft Research One Microsoft Way Redmond, WA, USA +1-(425)

Automatic Physical Design Tuning: Workload as a Sequence Sanjay Agrawal Microsoft Research One Microsoft Way Redmond, WA, USA +1-(425) Automati Physial Design Tuning: Workload as a Sequene Sanjay Agrawal Mirosoft Researh One Mirosoft Way Redmond, WA, USA +1-(425) 75-357 sagrawal@mirosoft.om Eri Chu * Computer Sienes Department University

More information

HEXA: Compact Data Structures for Faster Packet Processing

HEXA: Compact Data Structures for Faster Packet Processing Washington University in St. Louis Washington University Open Sholarship All Computer Siene and Engineering Researh Computer Siene and Engineering Report Number: 27-26 27 HEXA: Compat Data Strutures for

More information

Video Data and Sonar Data: Real World Data Fusion Example

Video Data and Sonar Data: Real World Data Fusion Example 14th International Conferene on Information Fusion Chiago, Illinois, USA, July 5-8, 2011 Video Data and Sonar Data: Real World Data Fusion Example David W. Krout Applied Physis Lab dkrout@apl.washington.edu

More information

Gray Codes for Reflectable Languages

Gray Codes for Reflectable Languages Gray Codes for Refletable Languages Yue Li Joe Sawada Marh 8, 2008 Abstrat We lassify a type of language alled a refletable language. We then develop a generi algorithm that an be used to list all strings

More information

represent = as a finite deimal" either in base 0 or in base. We an imagine that the omputer first omputes the mathematial = then rounds the result to

represent = as a finite deimal either in base 0 or in base. We an imagine that the omputer first omputes the mathematial = then rounds the result to Sientifi Computing Chapter I Computer Arithmeti Jonathan Goodman Courant Institute of Mathemaial Sienes Last revised January, 00 Introdution One of the many soures of error in sientifi omputing is inexat

More information

Pipelined Multipliers for Reconfigurable Hardware

Pipelined Multipliers for Reconfigurable Hardware Pipelined Multipliers for Reonfigurable Hardware Mithell J. Myjak and José G. Delgado-Frias Shool of Eletrial Engineering and Computer Siene, Washington State University Pullman, WA 99164-2752 USA {mmyjak,

More information

with respect to the normal in each medium, respectively. The question is: How are θ

with respect to the normal in each medium, respectively. The question is: How are θ Prof. Raghuveer Parthasarathy University of Oregon Physis 35 Winter 8 3 R EFRACTION When light travels from one medium to another, it may hange diretion. This phenomenon familiar whenever we see the bent

More information

A Novel Bit Level Time Series Representation with Implication of Similarity Search and Clustering

A Novel Bit Level Time Series Representation with Implication of Similarity Search and Clustering A Novel Bit Level Time Series Representation with Impliation of Similarity Searh and lustering hotirat Ratanamahatana, Eamonn Keogh, Anthony J. Bagnall 2, and Stefano Lonardi Dept. of omputer Siene & Engineering,

More information

Interconnection Styles

Interconnection Styles Interonnetion tyles oftware Design Following the Export (erver) tyle 2 M1 M4 M5 4 M3 M6 1 3 oftware Design Following the Export (Client) tyle e 2 e M1 M4 M5 4 M3 M6 1 e 3 oftware Design Following the Export

More information

- 1 - S 21. Directory-based Administration of Virtual Private Networks: Policy & Configuration. Charles A Kunzinger.

- 1 - S 21. Directory-based Administration of Virtual Private Networks: Policy & Configuration. Charles A Kunzinger. - 1 - S 21 Diretory-based Administration of Virtual Private Networks: Poliy & Configuration Charles A Kunzinger kunzinge@us.ibm.om - 2 - Clik here Agenda to type page title What is a VPN? What is VPN Poliy?

More information

A Novel Validity Index for Determination of the Optimal Number of Clusters

A Novel Validity Index for Determination of the Optimal Number of Clusters IEICE TRANS. INF. & SYST., VOL.E84 D, NO.2 FEBRUARY 2001 281 LETTER A Novel Validity Index for Determination of the Optimal Number of Clusters Do-Jong KIM, Yong-Woon PARK, and Dong-Jo PARK, Nonmembers

More information

Multiple Assignments

Multiple Assignments Two Outputs Conneted Together Multiple Assignments Two Outputs Conneted Together if (En1) Q

More information

Capturing Large Intra-class Variations of Biometric Data by Template Co-updating

Capturing Large Intra-class Variations of Biometric Data by Template Co-updating Capturing Large Intra-lass Variations of Biometri Data by Template Co-updating Ajita Rattani University of Cagliari Piazza d'armi, Cagliari, Italy ajita.rattani@diee.unia.it Gian Lua Marialis University

More information

Recursion examples: Problem 2. (More) Recursion and Lists. Tail recursion. Recursion examples: Problem 2. Recursion examples: Problem 3

Recursion examples: Problem 2. (More) Recursion and Lists. Tail recursion. Recursion examples: Problem 2. Recursion examples: Problem 3 Reursion eamples: Problem 2 (More) Reursion and s Reursive funtion to reverse a string publi String revstring(string str) { if(str.equals( )) return str; return revstring(str.substring(1, str.length()))

More information

Evolutionary Feature Synthesis for Image Databases

Evolutionary Feature Synthesis for Image Databases Evolutionary Feature Synthesis for Image Databases Anlei Dong, Bir Bhanu, Yingqiang Lin Center for Researh in Intelligent Systems University of California, Riverside, California 92521, USA {adong, bhanu,

More information

Graph-Based vs Depth-Based Data Representation for Multiview Images

Graph-Based vs Depth-Based Data Representation for Multiview Images Graph-Based vs Depth-Based Data Representation for Multiview Images Thomas Maugey, Antonio Ortega, Pasal Frossard Signal Proessing Laboratory (LTS), Eole Polytehnique Fédérale de Lausanne (EPFL) Email:

More information

NONLINEAR BACK PROJECTION FOR TOMOGRAPHIC IMAGE RECONSTRUCTION. Ken Sauer and Charles A. Bouman

NONLINEAR BACK PROJECTION FOR TOMOGRAPHIC IMAGE RECONSTRUCTION. Ken Sauer and Charles A. Bouman NONLINEAR BACK PROJECTION FOR TOMOGRAPHIC IMAGE RECONSTRUCTION Ken Sauer and Charles A. Bouman Department of Eletrial Engineering, University of Notre Dame Notre Dame, IN 46556, (219) 631-6999 Shool of

More information

The Minimum Redundancy Maximum Relevance Approach to Building Sparse Support Vector Machines

The Minimum Redundancy Maximum Relevance Approach to Building Sparse Support Vector Machines The Minimum Redundany Maximum Relevane Approah to Building Sparse Support Vetor Mahines Xiaoxing Yang, Ke Tang, and Xin Yao, Nature Inspired Computation and Appliations Laboratory (NICAL), Shool of Computer

More information

Department of Electrical Engineering and Computer Science MASSACHUSETTS INSTITUTE OF TECHNOLOGY Fall Test I Solutions

Department of Electrical Engineering and Computer Science MASSACHUSETTS INSTITUTE OF TECHNOLOGY Fall Test I Solutions Department of Eletrial Engineering and Computer iene MAACHUETT INTITUTE OF TECHNOLOGY 6.035 Fall 2016 Test I olutions 1 I Regular Expressions and Finite-tate Automata For Questions 1, 2, and 3, let the

More information

Approximate logic synthesis for error tolerant applications

Approximate logic synthesis for error tolerant applications Approximate logi synthesis for error tolerant appliations Doohul Shin and Sandeep K. Gupta Eletrial Engineering Department, University of Southern California, Los Angeles, CA 989 {doohuls, sandeep}@us.edu

More information

arxiv: v1 [cs.db] 13 Sep 2017

arxiv: v1 [cs.db] 13 Sep 2017 An effiient lustering algorithm from the measure of loal Gaussian distribution Yuan-Yen Tai (Dated: May 27, 2018) In this paper, I will introdue a fast and novel lustering algorithm based on Gaussian distribution

More information

Parametric Abstract Domains for Shape Analysis

Parametric Abstract Domains for Shape Analysis Parametri Abstrat Domains for Shape Analysis Xavier RIVAL (INRIA & Éole Normale Supérieure) Joint work with Bor-Yuh Evan CHANG (University of Maryland U University of Colorado) and George NECULA (University

More information

Improved Circuit-to-CNF Transformation for SAT-based ATPG

Improved Circuit-to-CNF Transformation for SAT-based ATPG Improved Ciruit-to-CNF Transformation for SAT-based ATPG Daniel Tille 1 René Krenz-Bååth 2 Juergen Shloeffel 2 Rolf Drehsler 1 1 Institute of Computer Siene, University of Bremen, 28359 Bremen, Germany

More information

DETECTION METHOD FOR NETWORK PENETRATING BEHAVIOR BASED ON COMMUNICATION FINGERPRINT

DETECTION METHOD FOR NETWORK PENETRATING BEHAVIOR BASED ON COMMUNICATION FINGERPRINT DETECTION METHOD FOR NETWORK PENETRATING BEHAVIOR BASED ON COMMUNICATION FINGERPRINT 1 ZHANGGUO TANG, 2 HUANZHOU LI, 3 MINGQUAN ZHONG, 4 JIAN ZHANG 1 Institute of Computer Network and Communiation Tehnology,

More information

Reducing Runtime Complexity of Long-Running Application Services via Dynamic Profiling and Dynamic Bytecode Adaptation for Improved Quality of Service

Reducing Runtime Complexity of Long-Running Application Services via Dynamic Profiling and Dynamic Bytecode Adaptation for Improved Quality of Service Reduing Runtime Complexity of Long-Running Appliation Servies via Dynami Profiling and Dynami Byteode Adaptation for Improved Quality of Servie ABSTRACT John Bergin Performane Engineering Laboratory University

More information

CA Test Data Manager 4.x Implementation Proven Professional Exam (CAT-681) Study Guide Version 1.0

CA Test Data Manager 4.x Implementation Proven Professional Exam (CAT-681) Study Guide Version 1.0 Implementation Proven Professional Study Guide Version 1.0 PROPRIETARY AND CONFIDENTIAL INFORMATION 2017 CA. All rights reserved. CA onfidential & proprietary information. For CA, CA Partner and CA Customer

More information

Anonymity Trilemma: Strong Anonymity, Low Bandwidth, Low Latency Choose Two

Anonymity Trilemma: Strong Anonymity, Low Bandwidth, Low Latency Choose Two Anonymity Trilemma: Strong Anonymity, Low Bandwidth, Low Lateny Choose Two Debajyoti Das Purdue University, USA das48@purdue.edu Sebastian Meiser University College London, U s.meiser@ul.a.uk Esfandiar

More information

Partial Character Decoding for Improved Regular Expression Matching in FPGAs

Partial Character Decoding for Improved Regular Expression Matching in FPGAs Partial Charater Deoding for Improved Regular Expression Mathing in FPGAs Peter Sutton Shool of Information Tehnology and Eletrial Engineering The University of Queensland Brisbane, Queensland, 4072, Australia

More information

On - Line Path Delay Fault Testing of Omega MINs M. Bellos 1, E. Kalligeros 1, D. Nikolos 1,2 & H. T. Vergos 1,2

On - Line Path Delay Fault Testing of Omega MINs M. Bellos 1, E. Kalligeros 1, D. Nikolos 1,2 & H. T. Vergos 1,2 On - Line Path Delay Fault Testing of Omega MINs M. Bellos, E. Kalligeros, D. Nikolos,2 & H. T. Vergos,2 Dept. of Computer Engineering and Informatis 2 Computer Tehnology Institute University of Patras,

More information

Multi-Piece Mold Design Based on Linear Mixed-Integer Program Toward Guaranteed Optimality

Multi-Piece Mold Design Based on Linear Mixed-Integer Program Toward Guaranteed Optimality INTERNATIONAL CONFERENCE ON MANUFACTURING AUTOMATION (ICMA200) Multi-Piee Mold Design Based on Linear Mixed-Integer Program Toward Guaranteed Optimality Stephen Stoyan, Yong Chen* Epstein Department of

More information

Effecting Parallel Graph Eigensolvers Through Library Composition

Effecting Parallel Graph Eigensolvers Through Library Composition Effeting Parallel Graph Eigensolvers Through Library Composition Alex Breuer, Peter Gottshling, Douglas Gregor, Andrew Lumsdaine Open Systems Laboratory Indiana University Bloomington, IN 47405 {abreuer,pgottsh,dgregor,lums@osl.iu.edu

More information

Calculation of typical running time of a branch-and-bound algorithm for the vertex-cover problem

Calculation of typical running time of a branch-and-bound algorithm for the vertex-cover problem Calulation of typial running time of a branh-and-bound algorithm for the vertex-over problem Joni Pajarinen, Joni.Pajarinen@iki.fi Otober 21, 2007 1 Introdution The vertex-over problem is one of a olletion

More information

A DYNAMIC ACCESS CONTROL WITH BINARY KEY-PAIR

A DYNAMIC ACCESS CONTROL WITH BINARY KEY-PAIR Malaysian Journal of Computer Siene, Vol 10 No 1, June 1997, pp 36-41 A DYNAMIC ACCESS CONTROL WITH BINARY KEY-PAIR Md Rafiqul Islam, Harihodin Selamat and Mohd Noor Md Sap Faulty of Computer Siene and

More information

SVC-DASH-M: Scalable Video Coding Dynamic Adaptive Streaming Over HTTP Using Multiple Connections

SVC-DASH-M: Scalable Video Coding Dynamic Adaptive Streaming Over HTTP Using Multiple Connections SVC-DASH-M: Salable Video Coding Dynami Adaptive Streaming Over HTTP Using Multiple Connetions Samar Ibrahim, Ahmed H. Zahran and Mahmoud H. Ismail Department of Eletronis and Eletrial Communiations, Faulty

More information

KERNEL SPARSE REPRESENTATION WITH LOCAL PATTERNS FOR FACE RECOGNITION

KERNEL SPARSE REPRESENTATION WITH LOCAL PATTERNS FOR FACE RECOGNITION KERNEL SPARSE REPRESENTATION WITH LOCAL PATTERNS FOR FACE RECOGNITION Cuiui Kang 1, Shengai Liao, Shiming Xiang 1, Chunhong Pan 1 1 National Laboratory of Pattern Reognition, Institute of Automation, Chinese

More information

Data Structures in Java

Data Structures in Java Data Strutures in Java Leture 8: Trees and Tree Traversals. 10/5/2015 Daniel Bauer 1 Trees in Computer Siene A lot of data omes in a hierarhial/nested struture. Mathematial expressions. Program struture.

More information

System-Level Parallelism and Throughput Optimization in Designing Reconfigurable Computing Applications

System-Level Parallelism and Throughput Optimization in Designing Reconfigurable Computing Applications System-Level Parallelism and hroughput Optimization in Designing Reonfigurable Computing Appliations Esam El-Araby 1, Mohamed aher 1, Kris Gaj 2, arek El-Ghazawi 1, David Caliga 3, and Nikitas Alexandridis

More information

UCSB Math TI-85 Tutorials: Basics

UCSB Math TI-85 Tutorials: Basics 3 UCSB Math TI-85 Tutorials: Basis If your alulator sreen doesn t show anything, try adjusting the ontrast aording to the instrutions on page 3, or page I-3, of the alulator manual You should read the

More information

The Happy Ending Problem

The Happy Ending Problem The Happy Ending Problem Neeldhara Misra STATUTORY WARNING This doument is a draft version 1 Introdution The Happy Ending problem first manifested itself on a typial wintery evening in 1933 These evenings

More information

the data. Structured Principal Component Analysis (SPCA)

the data. Structured Principal Component Analysis (SPCA) Strutured Prinipal Component Analysis Kristin M. Branson and Sameer Agarwal Department of Computer Siene and Engineering University of California, San Diego La Jolla, CA 9193-114 Abstrat Many tasks involving

More information

A Comparison of Hard-state and Soft-state Signaling Protocols

A Comparison of Hard-state and Soft-state Signaling Protocols University of Massahusetts Amherst SholarWorks@UMass Amherst Computer Siene Department Faulty Publiation Series Computer Siene 2003 A Comparison of Hard-state and Soft-state Signaling Protools Ping Ji

More information

Space- and Time-Efficient BDD Construction via Working Set Control

Space- and Time-Efficient BDD Construction via Working Set Control Spae- and Time-Effiient BDD Constrution via Working Set Control Bwolen Yang Yirng-An Chen Randal E. Bryant David R. O Hallaron Computer Siene Department Carnegie Mellon University Pittsburgh, PA 15213.

More information

A scheme for racquet sports video analysis with the combination of audio-visual information

A scheme for racquet sports video analysis with the combination of audio-visual information A sheme for raquet sports video analysis with the ombination of audio-visual information Liyuan Xing a*, Qixiang Ye b, Weigang Zhang, Qingming Huang a and Hua Yu a a Graduate Shool of the Chinese Aadamy

More information

RS485 Transceiver Component

RS485 Transceiver Component RS485 Transeiver Component Publiation Date: 2013/3/25 XMOS 2013, All Rights Reserved. RS485 Transeiver Component 2/12 Table of Contents 1 Overview 3 2 Resoure Requirements 4 3 Hardware Platforms 5 3.1

More information

Self-Adaptive Parent to Mean-Centric Recombination for Real-Parameter Optimization

Self-Adaptive Parent to Mean-Centric Recombination for Real-Parameter Optimization Self-Adaptive Parent to Mean-Centri Reombination for Real-Parameter Optimization Kalyanmoy Deb and Himanshu Jain Department of Mehanial Engineering Indian Institute of Tehnology Kanpur Kanpur, PIN 86 {deb,hjain}@iitk.a.in

More information

A {k, n}-secret Sharing Scheme for Color Images

A {k, n}-secret Sharing Scheme for Color Images A {k, n}-seret Sharing Sheme for Color Images Rastislav Luka, Konstantinos N. Plataniotis, and Anastasios N. Venetsanopoulos The Edward S. Rogers Sr. Dept. of Eletrial and Computer Engineering, University

More information

EXODUS II: A Finite Element Data Model

EXODUS II: A Finite Element Data Model SAND92-2137 Unlimited Release Printed November 1995 Distribution Category UC-705 EXODUS II: A Finite Element Data Model Larry A. Shoof, Vitor R. Yarberry Computational Mehanis and Visualization Department

More information

Re-programming a many-to-many merge with Hash Objects

Re-programming a many-to-many merge with Hash Objects Re-programming a many-to-many merge with Hash Objets CS05 PhUSE 2012 Budapest D. J. Garbutt 17 Otober 2012 Why? 1 In this talk I will demonstrate how you an re-program a many-to-many merge using hash objets

More information

Scheduling Multiple Independent Hard-Real-Time Jobs on a Heterogeneous Multiprocessor

Scheduling Multiple Independent Hard-Real-Time Jobs on a Heterogeneous Multiprocessor Sheduling Multiple Independent Hard-Real-Time Jobs on a Heterogeneous Multiproessor Orlando Moreira NXP Semiondutors Researh Eindhoven, Netherlands orlando.moreira@nxp.om Frederio Valente Universidade

More information

Colouring contact graphs of squares and rectilinear polygons de Berg, M.T.; Markovic, A.; Woeginger, G.

Colouring contact graphs of squares and rectilinear polygons de Berg, M.T.; Markovic, A.; Woeginger, G. Colouring ontat graphs of squares and retilinear polygons de Berg, M.T.; Markovi, A.; Woeginger, G. Published in: nd European Workshop on Computational Geometry (EuroCG 06), 0 Marh - April, Lugano, Switzerland

More information

Unsupervised Stereoscopic Video Object Segmentation Based on Active Contours and Retrainable Neural Networks

Unsupervised Stereoscopic Video Object Segmentation Based on Active Contours and Retrainable Neural Networks Unsupervised Stereosopi Video Objet Segmentation Based on Ative Contours and Retrainable Neural Networks KLIMIS NTALIANIS, ANASTASIOS DOULAMIS, and NIKOLAOS DOULAMIS National Tehnial University of Athens

More information

Make your process world

Make your process world Automation platforms Modion Quantum Safety System Make your proess world a safer plae You are faing omplex hallenges... Safety is at the heart of your proess In order to maintain and inrease your ompetitiveness,

More information

Introductory Programming, IMM, DTU Systematic Software Test. Software test (afprøvning) Motivation. Structural test and functional test

Introductory Programming, IMM, DTU Systematic Software Test. Software test (afprøvning) Motivation. Structural test and functional test Introdutory Programming, IMM, DTU Systemati Software Test Peter Sestoft a Programs often ontain unintended errors how do you find them? Strutural test Funtional test Notes: Systemati Software Test, http://www.dina.kvl.dk/

More information

Z8530 Programming Guide

Z8530 Programming Guide Z8530 Programming Guide Alan Cox alan@redhat.om Z8530 Programming Guide by Alan Cox Copyright 2000 by Alan Cox This doumentation is free software; you an redistribute it and/or modify it under the terms

More information

Stable Road Lane Model Based on Clothoids

Stable Road Lane Model Based on Clothoids Stable Road Lane Model Based on Clothoids C Gakstatter*, S Thomas**, Dr P Heinemann*, Prof Gudrun Klinker*** *Audi Eletronis Venture GmbH, **Leibniz Universität Hannover, ***Tehnishe Universität Münhen

More information

Title: Time-Based Tree Graphs for Stabilized Force Structure Representations

Title: Time-Based Tree Graphs for Stabilized Force Structure Representations Paper for the 8 th International Command & Control Researh & Tehnology Symposium Title: Time-Based Tree Graphs for Stabilized Fore Struture Representations Submitted by: Sam Chamberlain U.S. Army Researh

More information

CA Agile Requirements Designer 2.x Implementation Proven Professional Exam (CAT-720) Study Guide Version 1.0

CA Agile Requirements Designer 2.x Implementation Proven Professional Exam (CAT-720) Study Guide Version 1.0 Exam (CAT-720) Study Guide Version 1.0 PROPRIETARY AND CONFIDENTIAL INFORMATION 2017 CA. All rights reserved. CA onfidential & proprietary information. For CA, CA Partner and CA Customer use only. No unauthorized

More information

COST PERFORMANCE ASPECTS OF CCD FAST AUXILIARY MEMORY

COST PERFORMANCE ASPECTS OF CCD FAST AUXILIARY MEMORY COST PERFORMANCE ASPECTS OF CCD FAST AUXILIARY MEMORY Dileep P, Bhondarkor Texas Instruments Inorporated Dallas, Texas ABSTRACT Charge oupled devies (CCD's) hove been mentioned as potential fast auxiliary

More information

Improved Vehicle Classification in Long Traffic Video by Cooperating Tracker and Classifier Modules

Improved Vehicle Classification in Long Traffic Video by Cooperating Tracker and Classifier Modules Improved Vehile Classifiation in Long Traffi Video by Cooperating Traker and Classifier Modules Brendan Morris and Mohan Trivedi University of California, San Diego San Diego, CA 92093 {b1morris, trivedi}@usd.edu

More information

Back To LinkedLists 1. 3 public Node left; 4 public Node right; 6 public Node(int data, Node left, Node right) {

Back To LinkedLists 1. 3 public Node left; 4 public Node right; 6 public Node(int data, Node left, Node right) { Adam Blank Leture Autumn 0 CSE 3X Aelerated Computer Programming I/II CSE 3X: Aelerated Computer Programming I/II Binary Trees 0 00 00 00 00 0 000 00 00 0 00 0 000 000 000 0 0 00 0000 00 000 00 00 0 000

More information

3-D IMAGE MODELS AND COMPRESSION - SYNTHETIC HYBRID OR NATURAL FIT?

3-D IMAGE MODELS AND COMPRESSION - SYNTHETIC HYBRID OR NATURAL FIT? 3-D IMAGE MODELS AND COMPRESSION - SYNTHETIC HYBRID OR NATURAL FIT? Bernd Girod, Peter Eisert, Marus Magnor, Ekehard Steinbah, Thomas Wiegand Te {girod eommuniations Laboratory, University of Erlangen-Nuremberg

More information

Bring Your Own Coding Style

Bring Your Own Coding Style Bring Your Own Coding Style Naoto Ogura, Shinsuke Matsumoto, Hideaki Hata and Shinji Kusumoto Graduate Shool of Information Siene and Tehnology, Osaka University, Japan {n-ogura, shinsuke, kusumoto@ist.osaka-u.a.jp

More information

Performance Improvement of TCP on Wireless Cellular Networks by Adaptive FEC Combined with Explicit Loss Notification

Performance Improvement of TCP on Wireless Cellular Networks by Adaptive FEC Combined with Explicit Loss Notification erformane Improvement of TC on Wireless Cellular Networks by Adaptive Combined with Expliit Loss tifiation Masahiro Miyoshi, Masashi Sugano, Masayuki Murata Department of Infomatis and Mathematial Siene,

More information

CA PPM 14.x Implementation Proven Professional Exam (CAT-222) Study Guide Version 1.2

CA PPM 14.x Implementation Proven Professional Exam (CAT-222) Study Guide Version 1.2 CA PPM 14.x Implementation Proven Professional Exam (CAT-222) Study Guide Version 1.2 PROPRIETARY AND CONFIDENTIAL INFMATION 2016 CA. All rights reserved. CA onfidential & proprietary information. For

More information

OwnKit: Inferring Modularly Checkable Ownership Annotations for Java

OwnKit: Inferring Modularly Checkable Ownership Annotations for Java OwnKit: Inferring Modularly Chekable Ownership Annotations for Java Constantine Dymnikov Shool of Engineering and Computer Siene Vitoria University of Wellington Email: dymnikov@gmail.om David J. Peare

More information

Multi-Channel Wireless Networks: Capacity and Protocols

Multi-Channel Wireless Networks: Capacity and Protocols Multi-Channel Wireless Networks: Capaity and Protools Tehnial Report April 2005 Pradeep Kyasanur Dept. of Computer Siene, and Coordinated Siene Laboratory, University of Illinois at Urbana-Champaign Email:

More information

Semi-Supervised Affinity Propagation with Instance-Level Constraints

Semi-Supervised Affinity Propagation with Instance-Level Constraints Semi-Supervised Affinity Propagation with Instane-Level Constraints Inmar E. Givoni, Brendan J. Frey Probabilisti and Statistial Inferene Group University of Toronto 10 King s College Road, Toronto, Ontario,

More information

An Alternative Approach to the Fuzzifier in Fuzzy Clustering to Obtain Better Clustering Results

An Alternative Approach to the Fuzzifier in Fuzzy Clustering to Obtain Better Clustering Results An Alternative Approah to the Fuzziier in Fuzzy Clustering to Obtain Better Clustering Results Frank Klawonn Department o Computer Siene University o Applied Sienes BS/WF Salzdahlumer Str. 46/48 D-38302

More information

Test Case Generation from UML State Machines

Test Case Generation from UML State Machines Test Case Generation from UML State Mahines Dirk Seifert To ite this version: Dirk Seifert. Test Case Generation from UML State Mahines. [Researh Report] 2008. HAL Id: inria-00268864

More information

Dynamic Backlight Adaptation for Low Power Handheld Devices 1

Dynamic Backlight Adaptation for Low Power Handheld Devices 1 Dynami Baklight Adaptation for ow Power Handheld Devies 1 Sudeep Pasriha, Manev uthra, Shivajit Mohapatra, Nikil Dutt and Nalini Venkatasubramanian 444, Computer Siene Building, Shool of Information &

More information

Performance Benchmarks for an Interactive Video-on-Demand System

Performance Benchmarks for an Interactive Video-on-Demand System Performane Benhmarks for an Interative Video-on-Demand System. Guo,P.G.Taylor,E.W.M.Wong,S.Chan,M.Zukerman andk.s.tang ARC Speial Researh Centre for Ultra-Broadband Information Networks (CUBIN) Department

More information

Gradient based progressive probabilistic Hough transform

Gradient based progressive probabilistic Hough transform Gradient based progressive probabilisti Hough transform C.Galambos, J.Kittler and J.Matas Abstrat: The authors look at the benefits of exploiting gradient information to enhane the progressive probabilisti

More information

One Against One or One Against All : Which One is Better for Handwriting Recognition with SVMs?

One Against One or One Against All : Which One is Better for Handwriting Recognition with SVMs? One Against One or One Against All : Whih One is Better for Handwriting Reognition with SVMs? Jonathan Milgram, Mohamed Cheriet, Robert Sabourin To ite this version: Jonathan Milgram, Mohamed Cheriet,

More information

Total 100

Total 100 CS331 SOLUTION Problem # Points 1 10 2 15 3 25 4 20 5 15 6 15 Total 100 1. ssume you are dealing with a ompiler for a Java-like language. For eah of the following errors, irle whih phase would normally

More information

Type of document: Usebility Checklist

Type of document: Usebility Checklist Projet: JEGraph Type of doument: Usebility Cheklist Author: Max Bryan Version: 1.30 2011 Envidate GmbH Type of Doumet Developer guidelines User guidelines Dutybook Speifiation Programming and testing Test

More information

Sparse Certificates for 2-Connectivity in Directed Graphs

Sparse Certificates for 2-Connectivity in Directed Graphs Sparse Certifiates for 2-Connetivity in Direted Graphs Loukas Georgiadis Giuseppe F. Italiano Aikaterini Karanasiou Charis Papadopoulos Nikos Parotsidis Abstrat Motivated by the emergene of large-sale

More information

特集 Road Border Recognition Using FIR Images and LIDAR Signal Processing

特集 Road Border Recognition Using FIR Images and LIDAR Signal Processing デンソーテクニカルレビュー Vol. 15 2010 特集 Road Border Reognition Using FIR Images and LIDAR Signal Proessing 高木聖和 バーゼル ファルディ Kiyokazu TAKAGI Basel Fardi ヘンドリック ヴァイゲル Hendrik Weigel ゲルド ヴァニーリック Gerd Wanielik This paper

More information

Abstract. Key Words: Image Filters, Fuzzy Filters, Order Statistics Filters, Rank Ordered Mean Filters, Channel Noise. 1.

Abstract. Key Words: Image Filters, Fuzzy Filters, Order Statistics Filters, Rank Ordered Mean Filters, Channel Noise. 1. Fuzzy Weighted Rank Ordered Mean (FWROM) Filters for Mixed Noise Suppression from Images S. Meher, G. Panda, B. Majhi 3, M.R. Meher 4,,4 Department of Eletronis and I.E., National Institute of Tehnology,

More information