Getting a set of dependencies to a class deeply ne

2019-04-14 15:41发布

So here is my problem:

For instance, consider that:

A File has a set of Classes, as well as Imports.

A Class has a set of Instance Methods, Static Methods and Variables.

A Instance Method has Parameters and a Body.

The Body has ... yadayada.

The problem, when modelling this in a OO way is that Body may need a lot of specific dependencies to function:

class Body {
    ...

    public Body(Dependency1, Dependency2, Dependency_n, ...) { }

    ...
}

that all the other classes won't need, to run. The question I'm putting here is on how to get those dependencies to Body without having to pass all this dependencies through File, Class and InstanceMethod.

I could create a BodyFactory, but the problem would still be the same, as I'd have to pass the BodyFactory through File, Class and InstanceMethod, if I'm not missing anything.

How to solve this issue without resorting to singletons?

3条回答
Rolldiameter
2楼-- · 2019-04-14 16:19

As far as Java is concerned, I don't think you have a workaround here, if a method takes n parameters, then you are going to have to pass them, so you are going to have to carry them all the way, a solution to make this more elegant is to create a DataWrapper, call it BodyBean and pass it also all the way down.

Then you have the other option don't use parameters, then if these guys are singletons, just inject them, which by the way is the option I would recommend you

查看更多
我想做一个坏孩纸
3楼-- · 2019-04-14 16:28

It seems that you are dreaming about kind of injection framework. For example Spring Framework.

查看更多
兄弟一词,经得起流年.
4楼-- · 2019-04-14 16:45

Let Body implement an IBody interface and let InstanceMethod depend only on IBody and IEnumerable<IParameter> (if we assume C# - in Java it would be a differently named collection interface, but the principle would be the same).

Repeat this process of refactoring to Facade Services all the way to the Composition Root, where you can then compose the entire object graph like this:

File file = new File(
    new List<IClass>
    {
        new Class(
             new List<IInstanceMethod>
             {
                 new InstanceMethod(
                     new List<IParameter>(),
                     new Body(
                         new Dependency1()
                         new Dependency2(),
                         new DependencyN()))
             },
             new List<IStaticMethod>(),
             new List<IVariable>())
    },
    new List<IImport>());
查看更多
登录 后发表回答