#ifndef STATEPATTERNCOMPOSITION_H_INCLUDED #define STATEPATTERNCOMPOSITION_H_INCLUDED // static const char StatePatternComposition_h_RcsId[] = "$Id: StatePatternComposition.h,v 1.2 2003/01/16 04:54:25 neutron Exp $"; // // StatePatternComposition.h: // A template implementation of the State Design Pattern. // // Design: // This class contains three data members: A, B, and a bool // that says whether A or B is valid. // // C O N F I D E N T I A L // // Copyright 2002 Hewlett-Packard // // No part of this file may be reproduced, stored in a retrieval system, // or transmitted in any form or by any means--electronic, mechanical, // photocopying, recording, or otherwise--without prior written permission // of Hewlett Packard. // template class StatePatternComposition { protected: StatePatternComposition(); StatePatternComposition(const StatePatternComposition &); StatePatternComposition &operator=(const StatePatternComposition &); ~StatePatternComposition(); bool IsA() const; // Are we using an A? bool IsB() const; // Are we using a B? A *GetA(); // Return A *, assuming we have one. B *GetB(); // Return B *, assuming we have one. const A *GetA() const; // Return A *, assuming we have one. const B *GetB() const; // Return B *, assuming we have one. void SetA(); // Use A from now on. void SetB(); // Use B from now on. private: A a; B b; bool using_a; }; // Default constructor template inline StatePatternComposition::StatePatternComposition() : using_a(true) { } // Copy constructor template inline StatePatternComposition::StatePatternComposition(const StatePatternComposition &from) : a(from.a), b(from.b), using_a(from.using_a) { } // Assignment operator template inline StatePatternComposition &StatePatternComposition::operator=( const StatePatternComposition &from) { if (this != &from) { a = from.a; b = from.b; using_a = from.using_a; } return *this; } #include // Destructor template inline StatePatternComposition::~StatePatternComposition() { } // Do we point to an A? template inline bool StatePatternComposition::IsA() const { return using_a; } // Do we point to a B? template inline bool StatePatternComposition::IsB() const { return !using_a; } // Return an A *, assuming that we point to one. template inline A *StatePatternComposition::GetA() { assert(using_a); return &a; } // Return a B *, assuming that we point to one. template inline B *StatePatternComposition::GetB() { assert(!using_a); return &b; } // Return an A *, assuming that we point to one. template inline const A *StatePatternComposition::GetA() const { assert(using_a); return &a; } // Return a B *, assuming that we point to one. template inline const B *StatePatternComposition::GetB() const { assert(!using_a); return &b; } // Use A from now on. template inline void StatePatternComposition::SetA() { using_a = true; } // Use B from now on. template inline void StatePatternComposition::SetB() { using_a = false; } #endif /* STATEPATTERNCOMPOSITION_H_INCLUDED */