mercredi 12 juillet 2023

Proxy design pattern adding overhead when new APIs introduced

Im using proxy pattern to solve lazy loading problem. Trying to lazy initialize my class when member functions are invoked. I observe that if new api exposed in IOrder Interface, proxy class need to implement it and have initialization check which seems to be in-efficient, is there a better way to implement lazy initialization.

In text book example there is only one method which is considered to be doing heavy lifting task but in real time there could be many api which does heavy lifting so is there elegant way to check if realClass is initialized and forward the request to real class from proxy ?

class IOrder {
public:
    virtual OrderDetails get() = 0;
    virtual bool set(OrderDetails od) = 0;
}

class ProxyClass: public IOrder {
public:
    shared_ptr<RealClass> m_realClass;
    
    bool set(OrderDetails od) {
        if (nullptr == m_realClass) {
              m_realClass = std::make_shared<RealClass>();
              m_realClass->initialize();
        }
        m_realClass->set(od); // or by std::invoke
    }

    ...
}

class RealClass: public IOrder {
public:
    OrderDetails get() { ... }
    bool set(OrderDetails od) { ... }
    bool initialize() { ... }
}

Assume that if IOrder interface is exposed by some other library, if there is new api update then clients (proxy & real class) need to override it. Im looking for way to avoid proxy to override this. proxy bypass to real object if real object initialized.

Could not able to find results from google search for proxy design pattern lazy init issues.

Aucun commentaire:

Enregistrer un commentaire