mardi 17 août 2021

Is there a design pattern like this? [duplicate]

In a class inheritance, base class's protected member is not available to outside but is available to derived class.

Like this, I wanted to make derived class's public member not available to outside but available to base class.

I got an idea that if derived class's member function has parameters which is base class's inner class, then it'll behave like reverse-protected member while it's still public.

I adjusted this idea writing singleton class with CRTP pattern.

template <typename T>
class Singleton
{
public:
    static auto& getinst()
    {
        static T inst = no_constructor_call{};
        return inst;
    }
    Singleton(const Singleton&) = delete;
    void operator=(const Singleton&) = delete;
 
protected:
    struct no_constructor_call {};
    Singleton() {}
};

I made a singleton backbuffer for draw image via double-buffering with winapi.

#define BackBuffer _BackBuffer::getinst()
class _BackBuffer : public Singleton<_BackBuffer>
{
public:
    void Draw(HDC h_dc)
    {
        buf_dc = CreateCompatibleDC(h_dc);
        HBITMAP bit_buf{ CreateCompatibleBitmap(h_dc, client.right, client.bottom) };
        SelectObject(buf_dc, bit_buf);
        BitBlt(h_dc, 0, 0, client.right, client.bottom, buf_dc, 0, 0, SRCCOPY);
        DeleteObject(bit_buf);
        DeleteDC(buf_dc);
    }
    operator HDC() { return buf_dc; }
 
    _BackBuffer(Singleton<_BackBuffer>::no_constructor_call) {}
 
private:
    HDC buf_dc;
};
  • _BackBuffer(Singleton<_BackBuffer>::no_constructor_call) {}
    

this line made class _BackBuffer's constructor is not available to outside code but available to the Singleton base.

So I could create the _BackBuffer object in Singleton class while preventing other code creating _BackBuffer objects.

If I made the constructor private, it couldn't have created in it's base class.

And If I made the constructor perfectly public, it could have created in other code so it's not guarantee as singleton.

Now I'm regarding it can expandable to when you are wanting some public member function to be not available except some regions.

Is there a design pattern like this already existing?

Aucun commentaire:

Enregistrer un commentaire