您好,我在以更好的方式重构我的代码时遇到了问题,想在这里寻求帮助。
所以,我有一个接受 4 个不同接口(interface)的构造函数。
public Manager(FooSqlInterface foo, BarSqlInterface bar, MooSqlInterface moo, ZaaSqlInterface zaa)
{
this.foo = foo;
this.bar = bar;
this.moo = moo;
this.zaa = zaa;
}
但是,当我使用我的管理器时,我总是必须发送 4 个不同的接口(interface),但我每次只使用一个接口(interface)。
我仍然想使用我的管理器,但只是委托(delegate)构造函数接收的参数并将其传递给使用它的实际类。
有没有更好的方法在构造函数中只接受1个接口(interface),并根据它是哪个接口(interface),它会返回该类的一个实例。
像这样
public Manager(T type)
{
this.type = type;
execute();
}
public T execute()
{
if(type instanceof FooSqlInterface)
{
return Foo();
}
}
我试过编写类似这样的代码,但我无法让它工作。它只会给出未经检查的类型错误。
提前致谢!
最佳答案
如果可能,您可以尝试使用 super 接口(interface)吗?我试着做了一个简单的例子。
主要
public static void main(String[] args) throws ParseException {
A a = new AImpl();
B b = new BImpl();
C c = new CImpl();
Manager m1 = new Manager(a);
Manager m2 = new Manager(b);
Manager m3 = new Manager(c);
m1.doSomething();
m2.doSomething();
m3.doSomething();
}
super 界面
public interface Alphabetic {
void execute();
}
接口(interface)
public interface A extends Alphabetic {
void execute();
}
.
public interface B extends Alphabetic {
void execute();
}
.
public interface C extends Alphabetic {
void execute();
}
实现
public class AImpl implements A {
/* (non-Javadoc)
* @see tester.A#execute()
*/
@Override
public void execute() {
System.out.println("I am A");
}
}
.
public class BImpl implements B {
/* (non-Javadoc)
* @see tester.A#execute()
*/
@Override
public void execute() {
System.out.println("I am B");
}
}
.
public class CImpl implements C {
/* (non-Javadoc)
* @see tester.A#execute()
*/
@Override
public void execute() {
System.out.println("I am C");
}
}
输出
I am A
I am B
I am C
关于java - 委托(delegate)其参数的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28896445/