代码改变世界

[置顶] 把长方形的构造函数写的文艺点儿

2013-07-22 18:07  java20130722  阅读(291)  评论(1编辑  收藏  举报

文艺是一种感受,它来自路过看的人。

代码也如此,代码文艺不文艺,首先要从client code看。

假设我们想要实现一个长方形的构造函数,怎么能写的文艺点儿呢?


1.普通青年直接用构造函数

当你看到 new Rectangular(2.0, 4.0)的时候,你知道2.0和4.0是什么意思吗?

幸运的是这个类只有两个构造参数,还不算太猛。

如果类的field太多,只有进入Rectangular的类实现去看了。像我这种记性不好的,说不定一会儿就要看下,隔一会儿又要看下。



public class Rectangular {

    private final double length;
    private final double width;

    public Rectangular(double length, double width) {
        this.length = length;
        this.width = width;
    }
}



2.文艺青年用builder

        rectangular()
                .length(2.0)
                .width(4.0);

这样的调用,不用再怀疑,我传入的是length还是width了。这里使用的是builder模式。

builder是一种常用的建造对象的设计模式,GoF,Effective Java中都有讲。对于多个field的类,builder是一种不错的选择。


public class Rectangular {
    private double length;
    private double width;

    public static Rectangular rectangular() {
        return new Rectangular();
    }

    public Rectangular length(double length) {
        this.length = length;
        return this;
    }

    public Rectangular width(double width) {
        this.width = width;
        return this;
    }
}



3.文艺青年用嵌套方法

rectangular(length(2.0), width(4.0));

比起Method Chaining的方式,嵌套的方法不再使用Fluent Interface。


public class Rectangular {
    private final double length;
    private final double width;

    private Rectangular(double length, double width) {
        this.length = length;
        this.width = width;
    }

    public static double length(double length) {
        return length;
    }

    public static double width(double width) {
        return width;
    }

    public static Rectangular rectangular(double length, double width) {
        return new Rectangular(length, width);
    }
}


虽然length和width不能限制他传入的一定是相应的类型。但是也提供了一种可选的方法。

同时,当对象出现层次时,这种组织方式将变得更清晰。这是因为括号自己就可以显示出这样的层次。

比如:

        container(
                rectangular(length(2.0), length(4.0)),
                rectangular(length(1.0), length(3.0))
        )

这一点儿,是单纯使用第二种方法做不到或者不容易做到的。


也许你会说,你妹哦,我还不如写个json或者其他什么plain text来构造container。

恩,你这样想的话,就有点儿到点子上了。


多的不说了,上面的三种方式仅供参考,文艺和2B也只是一线之间。