ava中的构造函数重载-最佳实践

ava中的构造函数重载-最佳实践,第1张

ava中的构造函数重载-最佳实践

虽然没有“官方指导方针”,但我遵循亲干原则。使重载构造函数尽可能简单,最简单的方法是它们只调用this(…)。只需要检查一次参数

public class Simple {    public Simple() {        this(null);    }    public Simple(Resource r) {        this(r, null);    }    public Simple(Resource r1, Resource r2) {        // Guard statements, initialize resources or throw exceptions if        // the resources are wrong        if (r1 == null) { r1 = new Resource();        }        if (r2 == null) { r2 = new Resource();        }        // do whatever with resources    }}

从单元测试的角度来看,测试类变得很容易,因为您可以将资源放入其中。如果类有许多资源(或者一些OO极客所称的协作者),请考虑以下两件事情之一:

Make a parameter class

public class SimpleParams {    Resource r1;    Resource r2;    // Imagine there are setters and getters here but I'm too lazy     // to write it out. you can make it the parameter class     // "immutable" if you don't have setters and only set the     // resources through the SimpleParams constructor}

Simple中的构造函数只需要拆分

SimpleParams
参数:

public Simple(SimpleParams params) {    this(params.getR1(), params.getR2());}

…或将

SimpleParams
设为属性:

public Simple(Resource r1, Resource r2) {    this(new SimpleParams(r1, r2));}public Simple(SimpleParams params) {    this.params = params;}

Make a factory class

创建一个工厂类,为您初始化资源,如果初始化资源有点困难,这是有利的:

public interface ResourceFactory {    public Resource createR1();    public Resource createR2();}

然后以与参数类相同的方式完成构造函数:

public Simple(ResourceFactory factory) {    this(factory.createR1(), factory.createR2());} 

Make a combination of both

是 啊。。。你可以混合和匹配这两种方式,取决于什么是你当时更容易。参数类和简单工厂类几乎是同一回事,考虑到它们的使用方式相同。



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5487115.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-12
下一篇 2022-12-12

发表评论

登录后才能评论

评论列表(0条)

保存