Java – weave yourself into a corner

We have a set of classes derived from a set of common interfaces

IFoo-> BasicFoo,ReverseFoo,ForwardFoo
IBar -> UpBar,DownBar,SidewaysBar
IYelp -> Yip,Yap,Yup

The constructor of foo looks like foo (ibar, iyelp). These items are used in the whole project

There is another class. The signature of one of its methods is public double calcsomething (ifoo, ianotherclass), which is applied to a point of each foo We have proposed a specific object combination request from the above. Let's say that a basic foo (upbar, Yip) uses a different algorithm from calcsomething

My first instinct is to let us change the ifoo interface, so we can lower the logic to the foo class level, change the constructor to foo (ibar, iyelp, istrategy), and then let the foo object encapsulate the logic Unfortunately, we were also told that the design specification of the architecture, ifoo, has no dependency between its implementation and ianotherclass They insist on this

OK, of course, I thought I might use a visitor mode, but... How about? The whole point of making the work is that no other class can see the implementation details Reflect on the inside of the object and completely break the package? Oh, shit

So I came here because I was lost Does anyone have any suggestions on how we deal with the special case of a combination without modifying the composition or breaking the encapsulation? There must be a simple solution. I seem to go too far

Edit:

Removed the offending start Change to "special treatment" for more descriptive meaning

Solution

The calculationfactory that selects the appropriate algorithm according to the ifoo type you provide will solve the problem (at the cost of conditions):

interface ICalcSomethingStrategy {
    public double CalcSomething(IFoo,IAnotherClass);
}

CalcSomethingStrategyFactory {
    ICalcSomethingStrategy CreateCalcSomethingStrategy(IFoo foo) {
        // I'm not sure whether this is the idiomatic java way to check types D:
        if (foo.Bar instanceof UpBar && foo instanceof Yip) {
            return new UnusualCalcSomethingStrategy();
        } else {
            return new StandardCalcSomethingStrategy();
        }
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>