开发者

Forward declaration container used to simplify class constructors

开发者 https://www.devze.com 2022-12-18 11:06 出处:网络
I work on a huge legacy project. There are a number of classes that are created basically only once (they should be singletons, but oh well) and then passed around to almost every other class in the p

I work on a huge legacy project. There are a number of classes that are created basically only once (they should be singletons, but oh well) and then passed around to almost every other class in the program.

So there is lots of code like this where the class has a nearly endless list of pointers in its constructor

Foo(A* a, B * b, C * c, ...) 
   : Foo2(a,b,c),
     _a(a),
     _b(b),
     _c(c),
     ...,
{} 

I was thinking I could clean it up if I used an class to contain all of the pointers and use forward declaration to avoid creating more include dependencies. Each class could use the getters then to pull out anything they needed and include the appropriate headers.

//No includes required
class A;
class B;
class C;
class InterfaceMngr
{
public:
      InterfaceMngr(A * a, B * b, C* c)
       :_a(a),
        _b(b),
        _c(c)
      {
      }
     A * GetA() const { return _a; }
     B * GetB() const { return _b; }
     C * GetC() const { return _c; }

private:
     A * _a;
     B * _b;
     C * _c;
};

So the foo example would look something more like this now

Foo(Interface * inf) 
 : Foo2(inf),
   _a(inf->GetA()),
   _b(inf->GetB()),
   _c(inf->GetC())
{}

开发者_高级运维The nice thing is whenever a new class API comes into the picture I can just add it to Interface and don't need to change a few hundred constructors again....

Does anyone see an issue with this? I feel like I'm over exposing access to some classes, but it really simplifies editing the code.


I think you are looking at the Context design [anti-]pattern.


Don't be so quick to lament the lack of singletons. By passing object instances to your constructors, it makes it easier to perform unit tests.

If you are going to aggregate class pointers like that, perhaps you should consider making logical groups instead of one big catch-all interface aggregate. This will prevent having everything be dependent on everything else.

The Facade pattern may be of use to you as well.

0

精彩评论

暂无评论...
验证码 换一张
取 消