Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can refactor this:</p> <pre><code>if ( otherAObj.IsActive() ) { //do something with aObj } </code></pre> <p>out into a doSomething() function</p> <pre><code>public class A{ virtual bool isActive(){ return false; } virtual bool isPending(){ return false; } virtual void doSomething() { if(true == isActive()) { ... if(false == isPending()) { ... } ... } }; } public class A_State_Active : A { bool isActive(){ return true; } } public class A_State_Pending : A { bool isPending(){ return true; } void doSomething() { throw new InvalidOperationException("Don't be messing"); } } </code></pre> <p>Or even make the base version of doSomething pure virtual to force the users to implement a state specific version.</p> <p>However you should not implement anything in your subclasses that is based on the state of a different object. IMO you should use a manager type object in that case. If really want to do it that way you should just pass a reference to the other objects to the <code>doSomething()</code> function and modify the runtime behaviour based on the return values of the passed object's state (query using the "isActive"/"isPending" API).</p> <p>Other option is to do away with inheritance and favour composition. Have <code>A</code> be one class which holds a reference to an <code>A_State</code> class. You then subclass <code>A_State</code>. </p> <pre><code>class A { //public functions ... const A_State* getState(){ return m_poMyState; } void setState(const A_State const * aStateObj ){ m_poMyState = aStateObj; } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload