装饰图案与多个generics

我目前正在做一些代码重构。 所以我想通过decorator设计替换现有的inheritance设计。 但我正在努力解决多种仿制药(可能根本不可能)。

装饰器实现

我现在有上面的设计。 有一个IConstraint可以根据实现的约束来check sa类。 这些约束的具体实现是SimpleConstraintASimpleConstraintB ,它们都检查来自ClassA一些值。 Decorator增强了约束,例如,当指定值不在范围内时,有一些约束不应该被检查。 ClassA实现接口IAIB以便DecoratorADecoratorB可以使用它。

设计的用法如下:

 Test classToCheck = new Test("test"); IConstraint constraint = new DecoratorA(new DecoratorB(new SimpleConstraint())); boolean value = constraint.check(classToCheck); 

所以我想要的是使用具有不同数量的输入参数和不同类型的代码。 喜欢:

 Test classToCheckA = new Test("testA"); Test classToCheckB = new Test("testB"); IConstraint constraint = new DecoratorA(new DecoratorB(new SimpleConstraint())); boolean value = constraint.check(classToCheckA, classToCheckB); 

要么:

 Test classToCheckA = new Test("testA"); // TestB does implement the same interfaces as Test TestB classToCheckB = new TestB("testB"); IConstraint constraint = new DecoratorA(new DecoratorB(new SimpleConstraint())); boolean value = constraint.check(classToCheckA, classToCheckB); 

要么:

 Test classToCheckA = new Test("testA"); // TestB does implement the same interfaces as Test TestB classToCheckB = new TestB("testB"); // TestC does implement the same interfaces as Test TestC classToCheckC = new TestC("testC"); IConstraint constraint = new DecoratorA(new DecoratorB(new SimpleConstraint())); boolean value = constraint.check(classToCheckA, classToCheckB, classToCheckC); 

我尝试使用varargsListsObject[]代替check(obj:T)中的T check(obj:T)但后来我总是需要强制转换和大量的exception处理(例如输入参数的数量需要正确),所以我是不满意。

以下代码是我尝试过的一个例子。 就像你在SimpleConstraint看到的那样, check方法只允许使用类型( Test )。

 public interface IConstraint { public boolean check(T[] checkable); } public class SimpleConstraint implements IConstraint { @Override public boolean check(Test[] checkable) { return true; } } 

以上代码无法做到这一点:

 Test classToCheckA = new Test("testA"); // TestB does implement the same interfaces as Test TestB classToCheckB = new TestB("testB"); IConstraint constraint = new DecoratorA(new DecoratorB(new SimpleConstraint())); boolean value = constraint.check(classToCheckA, classToCheckB); 

设计是否有一些改进,以便可以支持不同数量的输入参数和不同类型?

在上面的代码中,问题是,Test和TestB没有共同的祖先……

 IConstraint constraint = ... boolean value = constraint.check(classToCheckA, classToCheckB); 

如果TestB extends Test或其他方式,您可以使其工作。

更好的方法是拥有

 IConstraint constraint =