有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java对象中构造函数发生变化时的设计模式最佳实践

我有一个类,其中根据新的api集成添加了许多参数

例如,之前我有一个带有4个参数的类:

Integer a;
String b;
Map<String, String> c;
List<Integer> e.

所以构造器是:

public SampleClass(Integer a, 
                   String b, 
                   Map<String, String> c,      
                   List<Integer> e) 
{
    this.a = a;
    this.b = b;
    this.c = c;
    this.e = e;
}

有几个团队在代码中使用这个构造函数与我的API进行了集成。 过了一段时间,这个类中添加了一个新参数。i、 e

Double d;

所以我添加了一个新的构造函数:

public SampleClass(Integer a,
                   String b,
                   Map<String, String> c,
                   List<Integer> e,
                   Double d)
{
    this.a = a;
    this.b = b;
    this.c = c;
    this.e = e;
    this.d = d;
}

我将之前的构造函数标记为已弃用。我没有删除之前的构造函数,因为如果删除,客户机的代码将中断

随着新参数的增加,我现在有了5个参数的构造函数

对于如何弃用/删除构造函数,以避免出现这种情况,是否有最佳实践


共 (1) 个答案

  1. # 1 楼答案

    将旧构造函数更改为:

    public SampleClass(Integer a, 
                       String b, 
                       Map<String, String> c,      
                       List<Integer> e) 
    {
        this.a = a;
        this.b = b;
        this.c = c;
        this.e = e;
    }
    

    public SampleClass(Integer a, 
                       String b, 
                       Map<String, String> c,      
                       List<Integer> e) 
    {
        //Zero is passed as a default value, but you can pass anything you want
        this(a,b,c,e,0);
    }
    

    这样它就可以称之为新的引擎盖下

    不过,您没有提供足够的信息,说明旧版本应该在多大程度上得到支持。如果根本不应该,您应该将其从代码中删除。通过这种方式,您将迫使API的用户分析发生了什么变化,并将新的构造函数连接起来

    如果不这样做,他们将继续使用旧版本,因为程序员很懒惰。:-)