lundi 14 mars 2022

How to create a wrapper or intermediate layer to access a class, without exposing it?

I use a third party engine, that has a class "Sprite". My classes use sprite, and call its methods.

There is a probability that "Sprite" will be replaced in the future by some other game engine. I would like to have a layer between my class, and Sprite, so that it is easy to swap out Sprite in future.

I figure there are at least two ways to do this:

  1. Implement a wrapper class that has a bridge method for every method in sprite, and that my code uses to access the sprite.

For Example:

Wrapper{
private:
Sprite* foo;
public:

  void method1(){
     foo->method1();
   }

   int method2(){
      return foo->method2();
    }
}

The downside with this approach is that there is a lot of work to write a method for each method in Sprite, even though all it is doing is just calling the method and returning whatever result. It is also a lot of maintenance work each time there is a change in sprite.

  1. Alternative 2 : Some kind of magic by overloading the -> operator.

     struct LoggingFoo : public Sprite {
     void log() const { } //Just a method for logging.Doesn't matter. 
    
    
     Foo const *operator -> () const { log(); return this; }
     Foo       *operator -> ()       { log(); return this; }
    

    };

Not very sure of all the things to keep in mind with this option ? For example, what happens to class methods ? Does it make sense to publicly inherit Sprite for this use case ?

Note: In practice, there is no object that is intended to inherit from Sprite in my code.

EDIT: What would be the most concise way to create the wrapper, yet expose all public member variables and functions? For example, not having to specify each and every variable and function to expose ?

Aucun commentaire:

Enregistrer un commentaire