编辑:
正在研究另一种方法(我认为它有同样的问题……)
嗯,你不可能真正得到你想要的,你需要在某些东西上进行权衡。
在这种情况下
apply
方法,该方法必须接受
Domain
.
这是因为
包裹
Service
不是在构造时设置的,因此不能100%键入。
interface Service<A extends Domain, B extends Domain> {
B apply(final Domain a);
Service<A, B> andThen(final Service<? extends Domain, ? extends Domain> service);
}
class MyService implements Service<A, B> {
private Service<? extends Domain, ? extends Domain> wrapped;
@Override
public B apply(final Domain a) {
return new B(a.name + "->B");
}
@Override
public Service<A, B> andThen(final Service<? extends Domain, ? extends Domain> wrapped) {
this.wrapped = wrapped;
return this;
}
}
class MyServiceDecorator1 implements Service<C, D> {
private Service<? extends Domain, ? extends Domain> wrapped;
@Override
public D apply(final Domain input) {
// C->A
Domain a = new A(input.name + "->A");
// get B
Domain b = this.wrapped.apply(a);
// B->D
return new D(b.name + "->D");
}
public Service<C, D> andThen(final Service<? extends Domain, ? extends Domain> wrapped) {
this.wrapped = wrapped;
return this;
}
}
class MyServiceDecorator2 implements Service<E, F> {
private Service<? extends Domain, ? extends Domain> wrapped;
@Override
public F apply(final Domain input) {
// E->C
Domain c = new C(input.name + "->C");
// get D
Domain d = this.wrapped.apply(c);
// D->F
return new F(d.name + "->F");
}
@Override
public Service<E, F> andThen(final Service<? extends Domain, ? extends Domain> wrapped) {
this.wrapped = wrapped;
return this;
}
}
public static void main(String[] args) {
final Service<A, B> myService = new MyService();
MyServiceDecorator1 myServiceDecorator1 = new MyServiceDecorator1();
MyServiceDecorator2 myServiceDecorator2 = new MyServiceDecorator2();
final Service<E, F> efService =
myServiceDecorator2.andThen(myServiceDecorator1)
.andThen(myService);
// This should still be doable i.e., the end goal
F f = efService.apply(new E("E"));
System.out.println(f.name);
}
我做得再好不过了,因为Java仅限于泛型功能。
结束语:字节码生成是你的朋友。