我有几个实现一些接口的类.现在我想创建一个新类,它可以在使用接口方法时根据运行时计算扩展其中一个类.我们在代码中谈谈:
public interface Interface {
public void doSomething();
}
public class A implements Interface {
@Override
public void doSomething() {
System.out.println("hello");
}
}
public class B implements Interface {
@Override
public void doSomething() {
System.out.println("hi");
}
}
Run Code Online (Sandbox Code Playgroud)
这些是现有的类,所以现在我需要做这样的事情(当然不行):
public class C<T extends Interface> extends T {
public void doSomethingElse() {
this.doSomething();
}
public static void main(String[] args) {
C c;
if(isSomethingLoaded) {
c = new C<A>();
} else {
c = new C<B>();
}
c.doSomethingElse();
}
}
Run Code Online (Sandbox Code Playgroud)
有可能以某种方式,除了我将参数接口传递给C的构造函数和存储到类属性的方式..?
类不能从其类型参数扩展.
使用组合而不是继承:
public class C<T extends Interface> {
private final T foo;
public C(T foo){
this.foo = foo;
}
public void doSomethingElse() {
foo.doSomething();
}
public static void main(String[] args) {
C<?> c;
if(isSomethingLoaded) {
c = new C<>(new A());
} else {
c = new C<>(new B());
}
c.doSomethingElse();
}
}
Run Code Online (Sandbox Code Playgroud)
你甚至可能不需要这里的type参数,只需使用接口类型作为参数/成员类型.
| 归档时间: |
|
| 查看次数: |
92 次 |
| 最近记录: |