开发者

What is the right design for two objects that share a dependency on another object?

I've been struggling with a design problem for a bit. I have an object Foo with an array of objects Bar. There are a series of calculation methods that are completely coupled to Foo, and depend on full knowledge of the array of Bar. So should I:

  • make a Calculator class and pass in the array of Bar objects. This seems bad to me because I can't test Calculator as a stand-alone unit, since Foo and Calculator both depend on the same array of Bar.

  • make a Calculator 开发者_如何学Pythonmodule and somehow extend Foo so that it includes Calculator? I haven't been able to figure out a good way to do that, where Calculator automatically has all of the knowledge of Foo that it needs. Is this possible?

  • just keep Calculator in Foo since it is so coupled to it.


Your architecture should not depend on object class but on interfaces.

The instance of Foo should in constructor require a parameter which implements interface iCalculator. And you method addBar should only require that you pass in to it something that implements iBar interface. And Calculator object ( which was passed to Foo ) should be able to perform calculate method on any instance of iBar object.

Now you can test all three object in isolation , if you provide Mocks with same interfaces.

The 'solution' actually is just application of Dependency inversion principle which is one of the which is one of the SOLID principles/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜