【发布时间】:2016-10-14 17:23:07
【问题描述】:
我目前正在做一些代码重构。所以我想用decorator 设计替换现有的inheritance 设计。但我正在为多种泛型而苦苦挣扎(也许根本不可能)。
我目前有上述设计。有IConstraint,其中checks 是一个针对已实施约束的类。这些约束的具体实现是SimpleConstraintA 和SimpleConstraintB,它们都在检查来自ClassA 的一些值。 Decorator 增强了约束,例如当指定值不在范围内时,不应检查某些约束。 ClassA 实现了接口IA 和IB 以便DecoratorA 和DecoratorB 可以使用它。
设计的用法如下:
Test classToCheck = new Test("test");
IConstraint<Test> constraint = new DecoratorA<>(new DecoratorB<>(new SimpleConstraint()));
boolean value = constraint.check(classToCheck);
所以我想要的是使用具有不同数量的输入参数和不同类型的代码。喜欢:
Test classToCheckA = new Test("testA");
Test classToCheckB = new Test("testB");
IConstraint<Test> 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<Test> 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<Test> constraint = new DecoratorA<>(new DecoratorB<>(new SimpleConstraint()));
boolean value = constraint.check(classToCheckA, classToCheckB, classToCheckC);
我尝试使用 varargs、Lists 或 Object[] 而不是来自 check(obj:T) 的 T,但我总是需要强制转换和大量异常处理(例如,输入参数的数量需要正确),所以我不满意。
以下代码是我尝试的一个示例。就像您在 SimpleConstraint 中看到的 check 方法一样,只允许使用类型 (Test)。
public interface IConstraint<T extends ICheckable> {
public boolean check(T[] checkable);
}
public class SimpleConstraint implements IConstraint<Test> {
@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<Test> constraint = new DecoratorA<>(new DecoratorB<>(new SimpleConstraint()));
boolean value = constraint.check(classToCheckA, classToCheckB);
设计上是否有一些改进,可以支持不同数量的输入参数和不同的类型?
【问题讨论】:
-
您能否详细说明“但我总是需要强制转换和大量异常处理”?我知道,这会使问题变得更长,但你应该提供一个代码 - 如果有人想尝试,他/她不需要创建他/她自己的......
-
@Betlista 我还没有完全实现
varargs、Lists或Object[]的解决方案,因此代码将无法运行。 -
@Betlista 我添加了一些示例代码。
-
因为你使用的是泛型,你不应该使用数组。请您展示您对
List的尝试,以及您看到的特定(编译器?)错误。 -
"例如输入参数的个数需要正确" 一般不能检查。如果您想在编译时强制执行特定数量的参数,则需要单独的约束接口:
Constraint1、Constraint2、Constraint3等。