lundi 27 février 2017

Name of pattern / well written?

I have the following code:

Doc header file

class CMyDoc
{
public:
    class Suspender
    {
        friend class CMyDoc;

        static bool m_suspending;
        inline static const bool IsSuspending() { return m_suspending; }

    public:
        Suspender()
        {
            m_suspending = true;
        }

        ~Suspender()
        {
            m_suspending = false;
        }
    };
}

Doc source file

Static variable initialization:

bool CMyDoc::Suspender::m_suspending = false;

Check if it is on the "not allowed" to do things state, and if so, don't do them:

void CMyDoc::SomeMethod()
{
    if (!Suspender::IsSuspending())
        DoThings();
}

Somewhere where I want to run some code on the "not allowed" state

Declare a variable of the Suspender type. Automatically will put on the "not allowed state" on the declaration. But the greatest benefit is it will return itself back to the "allowed" state when the stack frame ends, as it passes on the s variable's destructor.

void CMyView::DoSomething()
{
    CMyDoc::Suspender s;
    ((CMyDoc*) GetDocument())->SomeMethod();
}

QUESTIONS:

  1. What is the name of the pattern?
  2. Am I doing it in the most correct way? Can I avoid to have a static variable?

Aucun commentaire:

Enregistrer un commentaire