cxx3A

Embed Size (px)

Citation preview

  • 7/29/2019 cxx3A

    1/70

    AdvancedAdvanced C++C++

    ProgrammingProgramming

    Guillaume Caumon, September 2007Guillaume Caumon, September 2007

  • 7/29/2019 cxx3A

    2/70

    Introduction

    C++ supports a variety of programming styles:

    procedural (as FORTRAN, pascal, C, )procedural (as FORTRAN, pascal, C, )

    object-oriented (as Eifel, JAVA, )object-oriented (as Eifel, JAVA, )

    genericgeneric

    Features interact with each other.Features interact with each other.

    C++ is very flexible,C++ is very flexible, but also very confusing...but also very confusing...

  • 7/29/2019 cxx3A

    3/70

    Software development

    Energy = CostEnergy = Cost

    TimeTimeReleaseRelease

    Maintenance:Maintenance:- Bug fixesBug fixes- User requestsUser requests- Backward compatibilityBackward compatibility

    ConceptionConception

    DevelopmentDevelopment

    TestingTesting

  • 7/29/2019 cxx3A

    4/70

    Introduction

    The goal of this course is to provide some keys toThe goal of this course is to provide some keys to

    choose the design which:choose the design which:

    eases the maintenance process;eases the maintenance process;

    optimizes performance;optimizes performance;

    optimizes memory requirements.optimizes memory requirements.

  • 7/29/2019 cxx3A

    5/70

    Prerequisites

    A working knowledge of C++ and of the basicA working knowledge of C++ and of the basic

    object-oriented concepts.object-oriented concepts.

    What is a pointer ?What is a pointer ?

    What is a class ?What is a class ?

    What is inheritance ?What is inheritance ?

  • 7/29/2019 cxx3A

    6/70

    Outline

    Some Programming Rules

    Optimizing C++ programs

    Generic Programming A short STL overview

    Some Design Patterns

  • 7/29/2019 cxx3A

    7/70

    I- SomeI- Some C++ features andC++ features and

    programming rulesprogramming rules

    MiscellaneousMiscellaneous

    Object designObject design

  • 7/29/2019 cxx3A

    8/70

    Resolving ambiguities: namespace

    ANSI featureANSI featurenamespace Gocad1 {namespace Gocad1 {class MainWindow{ };class MainWindow{ };

    }}namespace Gocad2 {namespace Gocad2 {

    class MainWindow{ };class MainWindow{ };}}

    using namespace Gocad1;using namespace Gocad1;

    Gocad1::MainWindow window();Gocad1::MainWindow window();

    using Gocad2::MainWindow;using Gocad2::MainWindow;

  • 7/29/2019 cxx3A

    9/70

    References or pointers ?

    References are as cheap as pointers,References are as cheap as pointers,

    and more convenientand more convenient

    Rules:Rules: In function parameters, useIn function parameters, use

    const T& varconst T& varinstead ofinstead ofT varT varA nil reference does not exist, so use pointersA nil reference does not exist, so use pointers

    whenever you would need nil references.whenever you would need nil references. pointers can be reassigned, references cant.pointers can be reassigned, references cant.

    Goal: refer to objectsGoal: refer to objects

  • 7/29/2019 cxx3A

    10/70

    Exercise#include #include

    class Traced {class Traced {public:public:

    Traced();Traced();Traced( int parameter );Traced( int parameter );Traced( const Traced& rhs );Traced( const Traced& rhs );~Traced();~Traced();Traced& operator=( const Traced& rhs );Traced& operator=( const Traced& rhs );

    private:private:int impl_;int impl_;

    };};Using std::vector;Using std::vector;

    Class Dummy {Class Dummy {execute_val( vector flags );execute_val( vector flags );execute_p( vector* flags );execute_p( vector* flags );execute_ref( vector& flags );execute_ref( vector& flags );execute_cref( const vector& flags );execute_cref( const vector& flags );

    };};

    traced.h

  • 7/29/2019 cxx3A

    11/70

    Exerciseint main( int argc, char** argv ) {int main( int argc, char** argv ) {

    cout

  • 7/29/2019 cxx3A

    12/70

    Exceptions

    Goals : improve program safetyGoals : improve program safety

    try {try {// some code that might cause pbs// some code that might cause pbs

    }}

    throw messagethrow message

    catch ( message ) {catch ( message ) {// special processing Doctor Watson// special processing Doctor Watson

    }}

    How ? Framework to bypass the function call stackHow ? Framework to bypass the function call stack

  • 7/29/2019 cxx3A

    13/70

    Constructor and assignment

    int main() {int main() {String s1 = tutu;String s1 = tutu;String s2( toto );String s2( toto );s2 = s1;s2 = s1;

    };};

    class String {class String {public:public:

    String( const char* value );String( const char* value );String( const String& rhs );String( const String& rhs );~String();~String();

    String& operator=( const String& rhs);String& operator=( const String& rhs);private:private:

    char* data_;char* data_;};};

    file.h

  • 7/29/2019 cxx3A

    14/70

    Implicit type conversions

    class Rational {class Rational {

    Rational( int num, int denom = 1 );Rational( int num, int denom = 1 );double operator double() const;double operator double() const;

    };};void print_rational(void print_rational(

    ostream& out, const Rational& fractionostream& out, const Rational& fraction) {) {out num()

  • 7/29/2019 cxx3A

    15/70

    Avoiding implicit conversions

    class Rational {class Rational {explicit Rational(explicit Rational(

    int num,int num,int denom = 1int denom = 1

    ););operator double() const;operator double() const;

    };};

    ANSI featureANSI feature

  • 7/29/2019 cxx3A

    16/70

    Overloading operators (I)

    class Rational {class Rational {

    Rational& operator =( const Rational& rhs );Rational& operator =( const Rational& rhs );

    bool operator ==( const Rational& rhs );bool operator ==( const Rational& rhs );

    Rational operator +( const Rational& rhs );Rational operator +( const Rational& rhs );

    Rational& operator +=( const Rational& lhs );Rational& operator +=( const Rational& lhs );

    Rational& operator++(); // ++a (prefix)Rational& operator++(); // ++a (prefix)Rational operator++(int); // a++ (postfix)Rational operator++(int); // a++ (postfix)

    };};

  • 7/29/2019 cxx3A

    17/70

    Overloading operators (II)

    class Rational {class Rational {// // Rational operator+( int rhs );Rational operator+( int rhs );

    friend Rational operator+(friend Rational operator+(

    int lhs, const Rational& rhsint lhs, const Rational& rhs););

    };};

    Rational operator+(Rational operator+(int lhs, const Rational& rhsint lhs, const Rational& rhs

    ) { // }) { // }

    If the left-hand side of the expression is of a differentIf the left-hand side of the expression is of a different

    type, the operator MUST be a non-membertype, the operator MUST be a non-member

  • 7/29/2019 cxx3A

    18/70

    Modifying non const member in const

    member

    ANSI: use theANSI: use themutablemutable keywordkeyword

    Non ANSI: use const castNon ANSI: use const cast

    Downgrade the const memberDowngrade the const member

  • 7/29/2019 cxx3A

    19/70

    I-I- C++ main programmingC++ main programmingrulesrules

    MiscellaneousMiscellaneous

    Object designObject design

  • 7/29/2019 cxx3A

    20/70

    What is OOP?

    Object-Oriented Programming is a philosophyObject-Oriented Programming is a philosophy

    where the source code of a program is split intowhere the source code of a program is split into

    reusable objects.reusable objects.

    What is an object, then?What is an object, then?

    An object is made of two parts:An object is made of two parts:

    - The interfaceThe interface = catalog of the object features= catalog of the object features

    -The implementationThe implementation = internal machinery= internal machinery

  • 7/29/2019 cxx3A

    21/70

    The interface in C++

    Usually defined in a header (.h) file:Usually defined in a header (.h) file:

    class Car {class Car {public:public:

    //// MembersMembers can be accessed from any objectcan be accessed from any object

    protectedprotected:://// Can only be accessed by Car and its derived objectsCan only be accessed by Car and its derived objects

    privateprivate:://// Can only be accessed by Car for its own use.Can only be accessed by Car for its own use.

    };};

  • 7/29/2019 cxx3A

    22/70

    Aggregation or Composition?

    Aggregation is a relationship

    in which one object is a partof another.

    A aggregates BA aggregates B

    ==B is part of A, but theirB is part of A, but their

    lifetimes may be differentlifetimes may be different

    Ex: cEx: cars and wheels, engine,

    etc.

    Composition is a relationship

    in which one object is anintegral part of another

    A composes BA composes B

    ==

    B is part of A, and theirB is part of A, and their

    lifetimes are the samelifetimes are the same

    Ex: person and brain, lung,Ex: person and brain, lung,

    etc.etc.

    CarCar WheelWheel PersonPerson BrainBrain44

  • 7/29/2019 cxx3A

    23/70

    Classes: Basic Design Rules

    Minimize the number of public member functionsMinimize the number of public member functions

    Avoid default constructorsAvoid default constructors

    Hide implementation functions and dataHide implementation functions and data

    Hide all member variablesHide all member variables

    Avoid overloading (can be ambiguous)Avoid overloading (can be ambiguous)

    UseUse constconst members whenever possible / neededmembers whenever possible / needed

    Be aware of compiler generated functionsBe aware of compiler generated functions

  • 7/29/2019 cxx3A

    24/70

    Inheritance: quick review

    A circleA circle is ais a shapeshape

    CircleCircle

    GeomShapeGeomShape

    class GeomShape {class GeomShape {////

    };};

    class Circle : public GeomShape {class Circle : public GeomShape {////

    };};

    file.h

  • 7/29/2019 cxx3A

    25/70

    Public Inheritance Philosophy

    Public inheritancePublic inheritance is ais a

    In other words:In other words:

    What is applies to a base classWhat is applies to a base classapplies to its derived classesapplies to its derived classes

    Three aspects to consider:Three aspects to consider:class public interfaceclass public interface

    class relationship with derived classesclass relationship with derived classes

    class internal cookwareclass internal cookware

  • 7/29/2019 cxx3A

    26/70

    Polymorphism

    class Employee {class Employee {public :public :

    virtualvirtual float income();float income(); // 1000// 1000};};

    class Boss : public Employee {class Boss : public Employee {public :public :

    virtualvirtual float income();float income(); // 10000// 10000};};

    BossBoss

    EmployeeEmployee

    Mechanism that allows a derived class to modify theMechanism that allows a derived class to modify thebehavior of a member declared in a base classbehavior of a member declared in a base class

  • 7/29/2019 cxx3A

    27/70

    Polymorphism

    BossBoss

    EmployeeEmployee

    A pure virtual function just defines the interface, andA pure virtual function just defines the interface, andleaves the implementation to derived classesleaves the implementation to derived classes

    class Employee {class Employee {public :public :

    virtualvirtual float income() = 0;float income() = 0;// not implemented// not implemented

    };};class Boss : public Employee {class Boss : public Employee {

    public :public :virtualvirtual float income();float income(); // implemented// implemented

    };};

  • 7/29/2019 cxx3A

    28/70

    Public Inheritance PhilosophyInheritance of theinterface

    Inheritance of theimplementation

    Non virtualfunction

    Mandatory Mandatory

    Virtual function Mandatory By default,

    Possible to

    redefine

    Pure virtualfunction

    Mandatory Re-definition ismandatory

  • 7/29/2019 cxx3A

    29/70

    Private Inheritance Philosophy

    Private inheritancePrivate inheritance is implemented in term ofis implemented in term ofThis is an equivalent variant of agregation:This is an equivalent variant of agregation:

    class Car : private engine {class Car : private engine {////};};

    class Car {class Car {private:private:

    Engine engine_;Engine engine_;};};

  • 7/29/2019 cxx3A

    30/70

    Inheritance and fonctionsvirtual

    function

    pure virtual

    function

    Constructor

    is

    Destructor

    is

    Isolatedclass

    base class

    pureabstract

    class

    Derived(concrete)class

    publicpublic

    publicpublic

    virtualvirtual

    publicpublic

    virtualvirtual

    publicpublic

    virtualvirtual

    publicpublic

    publicpublic

    protectedprotected

    publicpublic

    NoNo

    NoNo

    Yes / noYes / no

    Yes/noYes/no

    YesYes

    (must)(must)

    YesYes

    (must)(must)

    YesYes

    (must)(must)

    NoNo

    cancanhave...have...

  • 7/29/2019 cxx3A

    31/70

    Polymorphism Mechanism

    Derived::vf1Derived::vf1

    Derived::vf3Derived::vf3

    DerivedDerived

    BaseBasevtbl_vtbl_

    Base::vf1Base::vf1

    Base::vf2Base::vf2

    Base::vf3Base::vf3

    BaseBasevtbl_vtbl_

  • 7/29/2019 cxx3A

    32/70

    Consequences

    Never call a virtual function in a constructorNever call a virtual function in a constructor

    Be aware of the increased size of classesBe aware of the increased size of classes

    with virtual functionswith virtual functions

    Calling a virtual function is more expensiveCalling a virtual function is more expensive

    than calling a non-virtual functionthan calling a non-virtual function

    Never declare a virtual function inlineNever declare a virtual function inline

  • 7/29/2019 cxx3A

    33/70

    Cast operators

    Avoid c-style casting operators.Avoid c-style casting operators.ANSI C++ provides 4 cast operators :ANSI C++ provides 4 cast operators :

    Type* reinterpret_cast(expression)Type* reinterpret_cast(expression)

    Type* static_cast(expression)Type* static_cast(expression)Type* const_cast(expression)Type* const_cast(expression)

    Type* dynamic_cast(expression)Type* dynamic_cast(expression)

  • 7/29/2019 cxx3A

    34/70

    Additional guidelines...

    Avoid multiple inheritance: use compositionAvoid multiple inheritance: use composition

    Forbid default parameters in virtual functionsForbid default parameters in virtual functions

    Dont redefine (overload) a non virtual functionDont redefine (overload) a non virtual function

    Differentiate between layering and inheritanceDifferentiate between layering and inheritance

  • 7/29/2019 cxx3A

    35/70

    II-II- Optimization in C++Optimization in C++

  • 7/29/2019 cxx3A

    36/70

    Optimization

    Main issue: algorithm complexity and memoryMain issue: algorithm complexity and memoryrequirementsrequirements

    Main question: which part of the code should beMain question: which part of the code should be

    optimized ?optimized ?

    20% of the code is used 80% of the time20% of the code is used 80% of the time

    Code maintenance and debug vs. optimization.Code maintenance and debug vs. optimization.

  • 7/29/2019 cxx3A

    37/70

    Lazy evaluation

    Compute only when neededCompute only when needed

    Examples:Examples:

    Matrix operator +Matrix operator +

    Gocad association mechanismGocad association mechanism

  • 7/29/2019 cxx3A

    38/70

    Anticipated evaluation

    Compute once, and cache information.Compute once, and cache information.

    Examples:Examples:

    Statistics managerStatistics manager

    Dynamic arraysDynamic arrays

  • 7/29/2019 cxx3A

    39/70

    Return value optimization

    class Complex {class Complex {////

    };};const Complex operator*(const Complex operator*(

    const Complex& a, const Complex bconst Complex& a, const Complex b) {) {

    Complex c;Complex c;

    c.set_real( a.real() * b.real() );c.set_real( a.real() * b.real() );c.set_im( a.im() + b.im() );c.set_im( a.im() + b.im() );return c;return c;

    }}

    A first try...A first try...

  • 7/29/2019 cxx3A

    40/70

    Return value optimization

    class Complex {class Complex {////

    };};const Complex& operator*(const Complex& operator*(

    const Complex& a, const Complex bconst Complex& a, const Complex b) {) {

    Complex c;Complex c;

    c.set_real( a.real() * b.real() );c.set_real( a.real() * b.real() );c.set_im( a.im() + b.im() );c.set_im( a.im() + b.im() );return c;return c;

    }}

    A second try...A second try...

  • 7/29/2019 cxx3A

    41/70

    Return value optimization

    class Complex {class Complex {////

    };};const Complex operator*(const Complex operator*(

    const Complex& a, const Complex bconst Complex& a, const Complex b) {) {

    return Complex(return Complex(

    a.real() * b.real(),a.real() * b.real(),a.im() + b.im()a.im() + b.im()

    ););}}

    A last try...A last try...

    ...But dont alter your code quality for that !!...But dont alter your code quality for that !!

  • 7/29/2019 cxx3A

    42/70

    Some rules...

    Overload to avoid implicit type conversions (fineOverload to avoid implicit type conversions (finetuning only)tuning only)

    Prefer operatorPrefer operator+=+= to operatorto operator++

    Prefer generic programming to virtual functionsPrefer generic programming to virtual functions

    Use inline functions, but not too much...Use inline functions, but not too much...

    Postpone variable declarationPostpone variable declaration

  • 7/29/2019 cxx3A

    43/70

    Example: dynamic arraysGoal: add items dynamically to a set.Goal: add items dynamically to a set.

    Problem:Problem:

    - dynamic memory allocation is time-consuming- dynamic memory allocation is time-consuming

    - the number of elements is not known from the start- the number of elements is not known from the start

    Proposal:Proposal:

    Allocate N elements, then add itemsAllocate N elements, then add items

    Allocate 2N elements, then copy existing items, then add itemsAllocate 2N elements, then copy existing items, then add items

    Allocate 4N elements, then copy existing items, then add itemsAllocate 4N elements, then copy existing items, then add items

  • 7/29/2019 cxx3A

    44/70

    III-III- Generic Programming in C++Generic Programming in C++

  • 7/29/2019 cxx3A

    45/70

    Parameterize classes

    Case of most container classes: store dataCase of most container classes: store dataof arbitrary types.of arbitrary types.

    template class List {template class List {public :public :List( int nb_items );List( int nb_items );~List();~List();

    void append_item( const T& item );void append_item( const T& item );void remove_item( const T& item );void remove_item( const T& item );void remove_all();void remove_all();////

    };};

    list.h

  • 7/29/2019 cxx3A

    46/70

    or fonctions

    /**/**

    * Swaps two objects of type T.* Swaps two objects of type T.* T should provide copy constructor* T should provide copy constructor* and operator=* and operator=*/*/

    template void swap(template void swap(

    T& t1, T& t2T& t1, T& t2););

    swap.h

    template void swap(template void swap(T& t1, T& t2T& t1, T& t2

    ) {) {T tmp(t1);T tmp(t1);t1 = t2;t1 = t2;t2 = tmp;t2 = tmp;

    }}

    swap.h

  • 7/29/2019 cxx3A

    47/70

    Templates

    Template code is compiled only when it isTemplate code is compiled only when it is

    used (used (template instanciationtemplate instanciation))

    Keyword class (or typename) or int canKeyword class (or typename) or int can

    be used to qualify template arguments.be used to qualify template arguments.

    Members can be required from templateMembers can be required from template

    argumentsarguments

  • 7/29/2019 cxx3A

    48/70

    Example

    template class List {template class List {////};};

    /**/**

    * Sorts a List of objects of type T.* Sorts a List of objects of type T.* T must provide order operators

  • 7/29/2019 cxx3A

    49/70

    Functors

    Goal: replace pointers to functionsGoal: replace pointers to functionsHow ?How ?

    [return type][return type]operator()(operator()( [type param][type param] ););

    Supports inline functionsSupports inline functionsType checkingType checking

    Example:Example:

    GeneratorGeneratorUnary FunctionUnary Function

    Binary functionBinary function

    PredicatesPredicates

  • 7/29/2019 cxx3A

    50/70

    Generic Programming

    Idea:Idea:

    Replace virtual functions by mandatoryReplace virtual functions by mandatory

    functions of template argumentsfunctions of template arguments

    Example: theExample: the GSTLGSTL[N. Rmy A. Shtuka B. Lvy [N. Rmy A. Shtuka B. Lvy J. Caers]J. Caers]

    http://var/www/apps/conversion/tmp/scratch_1/GsTL_gocad.ppthttp://var/www/apps/conversion/tmp/scratch_1/GsTL_gocad.ppthttp://var/www/apps/conversion/tmp/scratch_1/GsTL_gocad.ppt
  • 7/29/2019 cxx3A

    51/70

    Example: Matrix objects (1)class Matrix {class Matrix {

    public:public:virtual double operator()( int i, int j ) = 0;virtual double operator()( int i, int j ) = 0;

    };};

    class SymmetricMatrix : public Matrix {class SymmetricMatrix : public Matrix {

    Public:Public:virtual double operator()( int i, int j );virtual double operator()( int i, int j );

    };};

    class UpperTriangularMatrix : public Matrix {class UpperTriangularMatrix : public Matrix {public:public:virtual double operator()( int i, int j );virtual double operator()( int i, int j );

    };};

    Any problem?Any problem?

  • 7/29/2019 cxx3A

    52/70

    Static Polymorphism

    Replace virtual function by a template

    parameter

    Delegate the function to the template argument

  • 7/29/2019 cxx3A

    53/70

    Example: Matrix objects (2)class SymmetricStorage {class SymmetricStorage {

    public:public:double operator()( int i, int j );double operator()( int i, int j );

    };};class UpperTriangularMatrix {class UpperTriangularMatrix {////};};

    template class Matrix {template class Matrix {public:public:

    double operator()( int i, int j ) {double operator()( int i, int j ) {return storage_(i, j);return storage_(i, j);}}

    private:private:STORAGE storage_;STORAGE storage_;

    };};

    ( )

  • 7/29/2019 cxx3A

    54/70

    Example: Matrix objects (2)

    template class Matrix {template class Matrix {public:public:////bool is_invertible();bool is_invertible();

    bool is_sparse();bool is_sparse();bool is_symmetric_positive_definite();bool is_symmetric_positive_definite();

    ////};};

    Delegation toDelegation to STORAGESTORAGE::- Burdens theBurdens the STORAGESTORAGE conceptconcept- May end up with inconsistenciesMay end up with inconsistencies

    E l M i bj (3)

  • 7/29/2019 cxx3A

    55/70

    Example: Matrix objects (3)

    template class Matrix {template class Matrix {public:public:LEAF& leaf() {LEAF& leaf() {return static_cast( *this );return static_cast( *this );

    }}};};class SymmetricMatrix:class SymmetricMatrix:public Matrix {public Matrix {////

    };};

    Derived type is known at compile-timeDerived type is known at compile-time

    Derived classes can define their own functionsDerived classes can define their own functions

    T l t S i li ti

  • 7/29/2019 cxx3A

    56/70

    Template Specialization

    Redefine the implementation for some

    template arguments

    A li ti t

  • 7/29/2019 cxx3A

    57/70

    Application: metaprograms

    template class Factorial {template class Factorial {public:public:enum { value = N * Factorial::value };enum { value = N * Factorial::value };

    };};

    template class Factorial {template class Factorial {public:public:enum { value = 1 };enum { value = 1 };

    };};

    Void f() {Void f() {const int fact4 = Factorial::value;const int fact4 = Factorial::value;

    }}

    A li ti t

  • 7/29/2019 cxx3A

    58/70

    Application: metaprograms

    Practical interest:Practical interest:

    Specialization for optimizing behavior for small objectsSpecialization for optimizing behavior for small objects

    Example :Example :

    Expand loops in vector / tensor /matrix calculusExpand loops in vector / tensor /matrix calculus

  • 7/29/2019 cxx3A

    59/70

    IV-IV- Overview of the STLOverview of the STL

    I l d fil

  • 7/29/2019 cxx3A

    60/70

    Include files

    #include #include

    #include #include

    #include #include

    #include #include

    #include #include

    #include #include

    ..

    STL t i

  • 7/29/2019 cxx3A

    61/70

    STL containers

    std::vector vect(30);std::vector vect(30);

    vect[2] = 3;vect[2] = 3;

    ////

    for(for(

    std::vector::iterator it(vect.begin());std::vector::iterator it(vect.begin());

    it != vect.end(); it++it != vect.end(); it++) {) {

    int& cur_value = *it;int& cur_value = *it;

    }}

    STL l ith

  • 7/29/2019 cxx3A

    62/70

    STL algorithms

    OrderingOrdering

    PermutationsPermutations

    Search and replaceSearch and replace

  • 7/29/2019 cxx3A

    63/70

    V- Some design patternsV- Some design patterns

    Fi it t t hi

  • 7/29/2019 cxx3A

    64/70

    Finite state machine

    Class TransactionBased {Class TransactionBased {public:public:

    start_task1();start_task1();

    do_action1();do_action1();end_task1();end_task1();

    start_task2();start_task2(); // can be started only if task1 was completed// can be started only if task1 was completeddo_action2();do_action2();

    end_task2();end_task2();

    private:private:enum State{ UNDEF=0, TASK1=2, TASK2 = 4};enum State{ UNDEF=0, TASK1=2, TASK2 = 4};

    };};

    To solve a linear system of equationsTo solve a linear system of equations

    add equation coefficients one by one, then invert the matrixadd equation coefficients one by one, then invert the matrix

    C it

  • 7/29/2019 cxx3A

    65/70

    Composite

    GraphicGraphic

    TextText PicturePictureLineLine

    Treat a collection of objects as an objectTreat a collection of objects as an objectitselfitself

    Si l t

  • 7/29/2019 cxx3A

    66/70

    Singleton

    Ensure that an object is instantiated onlyEnsure that an object is instantiated onlyonceonce

    SingletonSingleton

    static Singleton* instance()static Singleton* instance()

    Obser er

  • 7/29/2019 cxx3A

    67/70

    Observer

    Define a dependency between objectsDefine a dependency between objects

    ConcreteObserverConcreteObserver

    SubjectSubjectnotify()notify()

    ObserverObserverupdate()update()

    Factory method

  • 7/29/2019 cxx3A

    68/70

    Factory method

    Create the right type of elements in anCreate the right type of elements in anabstract frameworkabstract framework

    CreatorCreatorcreate_product()create_product() ProductProduct

    ConcreteCreatorConcreteCreator ConcreteProductConcreteProduct

    Conclusions

  • 7/29/2019 cxx3A

    69/70

    Conclusions

    Concrete Applications...Concrete Applications...

    Programming projectProgramming project

    Oral presentation of the use of oneOral presentation of the use of one

    particular design pattern in Gocad (Dec 2,particular design pattern in Gocad (Dec 2,

    2005)2005)

    In your masters projectsIn your masters projects

    References

  • 7/29/2019 cxx3A

    70/70

    References

    Brokken et Kubat, C++ Annotations,http://www.icce.rug.nl/docs/cpp.shtml

    Stroustrup, Le langage C++ (3e ed.), AddissonWesley, 1996.

    Gamma et al., Design Patterns,Addisson Wesley,1995.

    Meyers, Effective C++,Addisson Wesley. Meyers, MoreEffective C++,Addisson Wesley. Meyers, Effective STL,Addisson Wesley. http://www.oonumerics.org/blitz/papers/ Gautieret al., Cours de Programmation par objets,

    Masson.

    http://www.icce.rug.nl/docs/cpp.shtmlhttp://www.oonumerics.org/blitz/papers/http://www.oonumerics.org/blitz/papers/http://www.icce.rug.nl/docs/cpp.shtml