栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

构造函数参数

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

构造函数参数

有那么多参数,该考虑构建器模式了。创建一个包含所有这些getter和setter的builder类,并带有一个build()方法,该方法返回您实际上试图构造的类的对象。

例:

public class ReallyComplicatedClass {    private int int1;    private int int2;    private String str1;    private String str2;    // ... and so on    // Note that the constructor is private    private ReallyComplicatedClass(Builder builder) {        // set all those variables from the builder    }    public static class Builder {        private int int1;        private int int2;        private String str1;        private String str2;        // and so on         public Builder() { // set required parameters        }        public Builder int1(int newInt) { int1 = newInt; return this;        }        // ... setters for all optional parameters, all returning 'this'        public ReallyComplicatedClass build() { return new ReallyComplicatedClass(this);        }    }}

在您的客户代码中:

ReallyComplicatedClass c = new ReallyComplicatedClass.Builder()        .int1(myInt1)        .str2(myStr2)        .build();

请参阅有效的Java重新加载
[pdf]的7-9页,这是Josh Bloch在JavaOne 2007上的演讲。(这也是有效的Java 2nd
Edition
中的第2项,但我没有用处,因此无法引用。)



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/373268.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号