我有一个接口(interface) Itest
和 ClassA
& ClassB
正在实现这个接口(interface)。 testA
和 testB
分别是这些类中的方法。
testA(String a, String b, String c, D d, E e)
testB(String a, String b, String c, F f, G g)
这里
D
、 E
、 F
、 G
是自定义数据类型(与数据库相关)。我简化了方法,实际上它们有更多的参数。我需要在
testAB
接口(interface)中的 Itest
中创建一个通用方法,并在两个类中实现它,而不是拥有自己的方法。testAB(String a, String b, String c, D d, E e, F f, G g)
由于参数数量较多,泛型方法
testAB
对用户来说将是痛苦的,因为他必须传递如此多的 null
值。最佳答案
看起来您的核心要求是您不希望客户端在不需要时传递其他参数。您可以使用普通的旧方法 overloading
解决您的问题:
更改您的 ITest
接口(interface)以拥有一个名为 test
的方法
public interface ITest {
public void test(String a,String b,String c,D d,E e,F f,G g);
}
更改
A
如下:public class A implements ITest {
//this is an overload - v1
public void test(String a,String b,String c,D d,E e) {
//dispatch the call to the overriden method
test(a,b,c,d,e,null,null);
}
//this is an overload - v2
public void test(String a,String b,String c,E e,F f) {
//dispatch the call to the overriden method
test(a,b,c,null,null,e,f);
}
@Override
//this is an overriden method - v3
public void test(String a,String b,String c,D d,E e,F f,G g) {
if(d!=null && e!=null) {
//use a,b,c,d,e and do something
}
if(f!=null && g!=null) {
//use a,b,c,f,g and do something
}
}
}
现在客户端代码可以调用他们想要的任何重载形式,而无需传递
null
。您的重载方法将简单地将调用分派(dispatch)到公共(public)方法(这为您提供了代码重用的优势):classAObj.test("1","2","3",new D(),new E());//calls overloaded method - v1
classAObj.test("1","2","3",new F(),new G());//calls overloaded method - v2
classAObj.test("1","2","3",new D(),new E(),new F(),new G());//calls overriden method - v3
请注意客户端代码如何不必担心在不需要时传递额外的参数。还要注意客户端调用看起来有多干净。
B
中也可以进行类似的更改。1. 您可以选择使
ITest
成为抽象类。这将允许您使其中的 test
方法具有 protected
访问说明符。需要 protected
访问说明符的原因是为了限制客户端类能够访问该方法并始终通过重载的形式。这是一个附加功能,如果您现在坚持使用 interface
,您可以考虑在将来实现。2.您还可以利用
Generics
避免每次引入新对象类型时都需要编写新类,但正如您从其他答案中看到的那样,这很容易在很大程度上使您的代码复杂化。您还可以将重载方法添加到 ITest
接口(interface),使其成为其契约的一部分。但是,我故意将这些部分排除在我的答案之外,因为您的问题的症结可以通过使用 overloading
来解决。3.
Builder
模式是一种创建模式。在这种特殊情况下,这是一种矫枉过正,因为诸如 D
、 E
、 F
和 G
之类的类是域对象。 A
和 B
类在真正意义上并不真正依赖它们,而是将它们用作数据源。关于java - 构建器设计模式为具有大量参数的方法制作通用方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30639947/