JAVA构造对象的几种方式(构建器、构造器)

大家好,我是烤鸭:

    今天说一下初始化对象的几种方式:

        1.    多参数构造器

        2.    构建器

        3.    构造器后 + get/set方法


举个例子:

    这里有个机构entity,提供一个默认构造器

package com.xxx.xxx.modules.sys.entity;/*** 机构Entity* @version 2013-05-15*/
public class Office {private static final long serialVersionUID = 1L;private Area area;		// 归属区域private String code; 	// 机构编码private String type; 	// 机构类型(1:公司;2:部门;3:小组)private String grade; 	// 机构等级(1:一级;2:二级;3:三级;4:四级)private String address; // 联系地址private String zipCode; // 邮政编码private String master; 	// 负责人private String phone; 	// 电话private String fax; 	// 传真private String email; 	// 邮箱private String useable;//是否可用private User primaryPerson;//主负责人private User deputyPerson;//副负责人private List<String> childDeptList;//快速添加子部门private String officeCode; //新增字段,门店id,和code值一样private String businessArea; //2.0新增字段,营业面积private String businessHours; //2.0新增字段,营业时间public Office(){super();}
}

如果想创建一个这样的对象进行参数传递或者进行其他操作(数据库等等)


1.   多参数构造器

       这是全参构造器:

public Office(Area area, String code, String type, String grade, String address, String zipCode, String master, String phone, String fax, String email, String useable, User primaryPerson, User deputyPerson, List<String> childDeptList, String officeCode, String businessArea, String businessHours, String jxName) {this.area = area;this.code = code;this.type = type;this.grade = grade;this.address = address;this.zipCode = zipCode;this.master = master;this.phone = phone;this.fax = fax;this.email = email;this.useable = useable;this.primaryPerson = primaryPerson;this.deputyPerson = deputyPerson;this.childDeptList = childDeptList;this.officeCode = officeCode;this.businessArea = businessArea;this.businessHours = businessHours;this.jxName = jxName;}


2.   构建

     这是全参构建器:

private Office(Office.Builder builder){this.id = builder.id;this.area = builder.area;this.code = builder.code;this.type = builder.type;this.grade = builder.grade;this.address = builder.address;this.name = builder.name;this.email = builder.email;this.phone = builder.phone;this.zipCode = builder.zipCode;this.master = builder.master;this.parent = builder.parent;this.parentIds = builder.parentIds;this.fax = builder.fax;this.sort = builder.sort;this.primaryPerson = builder.primaryPerson;this.deputyPerson = builder.deputyPerson;this.childDeptList = builder.childDeptList;this.officeCode = builder.officeCode;this.businessArea = builder.businessArea;this.useable = builder.useable;this.businessHours = builder.businessHours;this.delFlag = builder.delFlag;this.createBy = builder.createBy;this.updateBy = builder.updateBy;this.updateDate = builder.updateDate;this.createDate = builder.createDate;}//利用构建器创建对象public static class Builder extends Office{private static final long serialVersionUID = 1L;private Area area;		// 归属区域private String code; 	// 机构编码private String type; 	// 机构类型(1:公司;2:部门;3:小组)private String grade; 	// 机构等级(1:一级;2:二级;3:三级;4:四级)private String address; // 联系地址private String zipCode; // 邮政编码private String master; 	// 负责人private String phone; 	// 电话private String fax; 	// 传真private String email; 	// 邮箱private String useable;//是否可用private User primaryPerson;//主负责人private User deputyPerson;//副负责人private List<String> childDeptList;//快速添加子部门private String officeCode; //新增字段,门店id,和code值一样private String businessArea; //2.0新增字段,营业面积private String businessHours; //2.0新增字段,营业时间public Builder() {super();}public Builder id(String id){this.id = id;return this;}public Office build(){return new Office(this);}public Builder area(Area area){this.area = area;return this;}public Builder name(String name) {this.name = name;return this;}public Builder master(String master) {this.master = master;return this;}public Builder code(String code) {this.code = code;return this;}public Builder type(String type){this.type = type;return this;}public Builder grade(String grade) {this.grade = grade;return this;}public Builder address(String address) {this.address = address;return this;}public Builder zipCode(String zipCode) {this.zipCode = zipCode;return this;}public Builder password(String master) {this.master = master;return this;}public Builder parent(Office parent) {this.parent = parent;return this;}public Builder parentIds(String parentIds) {this.parentIds = parentIds;return this;}public Builder phone(String phone) {this.phone = phone;return this;}public Builder fax(String fax) {this.fax = fax;return this;}public Builder email(String email) {this.email = email;return this;}public Builder useable(String useable) {this.useable = useable;return this;}public Builder sort(Integer sort) {this.sort = sort;return this;}public Builder primaryPerson(User primaryPerson) {this.primaryPerson = primaryPerson;return this;}public Builder deputyPerson(User deputyPerson) {this.deputyPerson = deputyPerson;return this;}public Builder childDeptList(List<String> childDeptList) {this.childDeptList = childDeptList;return this;}public Builder officeCode(String officeCode) {this.officeCode = officeCode;return this;}public Builder businessArea(String businessArea) {this.businessArea = businessArea;return this;}public Builder businessHours(String businessHours) {this.businessHours = businessHours;return this;}public Builder delFlag(String delFlag) {this.delFlag = delFlag;if(StringUtils.isBlank(delFlag)){this.delFlag = IDBConstant.APPLICATION_DELETE_FLAG_VALID + "";}return this;}public Builder createBy(User createBy) {this.createBy = createBy;return this;}public Builder updateBy(User updateBy) {this.updateBy = updateBy;return this;}public Builder createDate(Date createDate) {this.createDate = createDate;return this;}public Builder updateDate(Date updateDate) {this.updateDate = updateDate;return this;}}


3.   get/set方法

     自动生成就行
        public List<String> getChildDeptList() {return childDeptList;}public void setChildDeptList(List<String> childDeptList) {this.childDeptList = childDeptList;}public String getUseable() {return useable;}public void setUseable(String useable) {this.useable = useable;}public User getPrimaryPerson() {return primaryPerson;}public void setPrimaryPerson(User primaryPerson) {this.primaryPerson = primaryPerson;}public User getDeputyPerson() {return deputyPerson;}public void setDeputyPerson(User deputyPerson) {this.deputyPerson = deputyPerson;}public Office getParent() {return parent;}public void setParent(Office parent) {this.parent = parent;}@NotNullpublic Area getArea() {return area;}public void setArea(Area area) {this.area = area;}@Length(min=1, max=1)public String getType() {return type;}public void setType(String type) {this.type = type;}@Length(min=1, max=1)public String getGrade() {return grade;}public void setGrade(String grade) {this.grade = grade;}@Length(min=0, max=255)public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}@Length(min=0, max=100)public String getZipCode() {return zipCode;}public void setZipCode(String zipCode) {this.zipCode = zipCode;}@Length(min=0, max=100)public String getMaster() {return master;}public void setMaster(String master) {this.master = master;}@Length(min=0, max=200)public String getPhone() {return phone;}public void setPhone(String phone) {this.phone = phone;}@Length(min=0, max=200)public String getFax() {return fax;}public void setFax(String fax) {this.fax = fax;}@Length(min=0, max=200)public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}@Length(min=0, max=100)public String getCode() {return code;}public void setCode(String code) {this.code = code;}@Overridepublic String toString() {return name;}public String getOfficeCode() {return officeCode;}public void setOfficeCode(String officeCode) {this.officeCode = officeCode;}public String getBusinessArea() {return businessArea;}public void setBusinessArea(String businessArea) {this.businessArea = businessArea;}public String getBusinessHours() {return businessHours;}public void setBusinessHours(String businessHours) {this.businessHours = businessHours;}
}public List<String> getChildDeptList() {return childDeptList;}public void setChildDeptList(List<String> childDeptList) {this.childDeptList = childDeptList;}public String getUseable() {return useable;}public void setUseable(String useable) {this.useable = useable;}public User getPrimaryPerson() {return primaryPerson;}public void setPrimaryPerson(User primaryPerson) {this.primaryPerson = primaryPerson;}public User getDeputyPerson() {return deputyPerson;}public void setDeputyPerson(User deputyPerson) {this.deputyPerson = deputyPerson;}public Office getParent() {return parent;}public void setParent(Office parent) {this.parent = parent;}@NotNullpublic Area getArea() {return area;}public void setArea(Area area) {this.area = area;}@Length(min=1, max=1)public String getType() {return type;}public void setType(String type) {this.type = type;}@Length(min=1, max=1)public String getGrade() {return grade;}public void setGrade(String grade) {this.grade = grade;}@Length(min=0, max=255)public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}@Length(min=0, max=100)public String getZipCode() {return zipCode;}public void setZipCode(String zipCode) {this.zipCode = zipCode;}@Length(min=0, max=100)public String getMaster() {return master;}public void setMaster(String master) {this.master = master;}@Length(min=0, max=200)public String getPhone() {return phone;}public void setPhone(String phone) {this.phone = phone;}@Length(min=0, max=200)public String getFax() {return fax;}public void setFax(String fax) {this.fax = fax;}@Length(min=0, max=200)public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}@Length(min=0, max=100)public String getCode() {return code;}public void setCode(String code) {this.code = code;}@Overridepublic String toString() {return name;}public String getOfficeCode() {return officeCode;}public void setOfficeCode(String officeCode) {this.officeCode = officeCode;}public String getBusinessArea() {return businessArea;}public void setBusinessArea(String businessArea) {this.businessArea = businessArea;}public String getBusinessHours() {return businessHours;}public void setBusinessHours(String businessHours) {this.businessHours = businessHours;}


4.    用法

        如果我想构造一个对象

    4.1    构造器

        直接上图吧:

    

    当我new Office()的时候,我不知道需要传入什么类型的参数,也不知道每个参数代表哪个字段。

多个字段的时候,不推荐这种方式。几个字段算多?我觉得5+吧。

    4.2    构建器

    

        上图的字段比例子中的多了几个, 构建器构造的对象很清晰,而且相对利于维护,构造器的话,需要修改构造方法,构建器在builder对象中加属性就好了。为什么说构建器更安全,因为一个对象在可能有多个构造器,通过构造器来创建,没法保证一致性。比如:new Office(id)和new Office(name),这两个对象怎么保证一致呢。

    4.3    get/set方法

        不演示了,就拿上图来说,set属性需要多少行代码?起码多两倍不止。


5.    关于构建器和构造器

    JavaBean模式自身有严重的缺点,因为构造过程被分到几个调用中,在构造过程中Javabean可能处于不一致的状态,类无法仅仅通过检验构造器参数的有效性来保证一致性。JavaBean模式阻止了把类做成不可变的可能,这就需要程序员付出额外的努力确保线程安全 。

Java中传统的抽象工厂实现是Class对象,newInstance方法总是企图调用类的无参构造器,这个构造器甚至可能根本不存在。Class.newInstance破坏了编译时的异常检查。Builder模式也存在不足。为了创建对象,必须先创建它的构建器。在十分注重性能的情况下,可能就成问题了。Builder模式还比重叠构造器模式更加冗长,因此它只在有很多参数的时候才使用,比如4个或者更多个参数。通常最好一开始就使用构建器。

  如果类的构造器或者静态工厂中具有多个参数,设计这种类时,Builder模式就是种不错的选择,特别是当大多数参数都是可选的时候。与使用传统的重叠构造器模式相比,使用Builder模式的客户端代码将更易于阅读和编写,构建器也比JavaBeans更加安全。


 参考资料

《Effective Java 中文版 第2版》 


        

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/412952.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Django框架(十二)-- Djang与Ajax

一、什么是Ajax AJAX&#xff08;Asynchronous Javascript And XML&#xff09;翻译成中文就是“异步Javascript和XML”。即使用Javascript语言与服务器进行异步交互&#xff0c;传输的数据为XML&#xff08;当然&#xff0c;传输的数据不只是XML,现在更多使用json数据&#xf…

javascript 将table导出 Excel ,可跨行跨列

原文地址&#xff1a;https://www.cnblogs.com/hailexuexi/p/10795887.html <script language"JavaScript" type"text/javascript">//jQuery HTML导出Excel文件(兼容IE及所有浏览器)function HtmlExportToExcel(tableid,file_name) {var filename fi…

wampserver 搭建 php环境 运行方法

大家好&#xff0c;我是烤鸭&#xff1a;今天分享的是如何用wamp 运行 php代码。1. wampserver下载&#xff1a;下载地址&#xff1a;https://sourceforge.net/projects/wampserver/files/WampServer%203/WampServer%203.0.0/Addons/Php/wampserver3_x64_addon_php7.2.7.exe…

java php des加密 byte数组16进制 DESTools

大家好&#xff0c;我是烤鸭:今天分享的是java 和 php des 加密。因为接口对接&#xff0c;难免不同语言&#xff0c;加密又是必不可少的。作为接口的提供方&#xff0c;必须把加密规则写好&#xff0c;最好有不同语言的加密demo。1. java版本的des加密解密工具类DESTools.j…

高可用Eureka注册中心配置说明(双机部署)

目 录 1. 高可用EureKa注册中心示意图 2. Eureka实例相互注册配置 3. 微服务注册到Eureka配置 4. 启动步骤及配置成功检查 5. 说明事项 1. 高可用EureKa注册中心示意图 Spring Cloud的Eureka Server的高可用实际上就是将自己作为服务向其他服注册中心注册自己&#xff0c;形成…

java 实现 常见排序算法(一) 冒泡排序

大家好&#xff0c;我是烤鸭&#xff1a; 今天分享一下基础排序算法之冒泡排序。 1. 冒泡排序&#xff1a; 原理&#xff1a;比较两个相邻的元素&#xff0c;将较大的元素交换至右端。 思路&#xff1a;依次比较相邻的两个数&#xff0c;将小数放在前面&#xff0c;大…

vue学习之npm

任何一门计算机语言都包含了丰富的第三方库&#xff0c;npm就是JavaScript这门语言的第三方库管理工具&#xff0c;本文详细介绍了JavaScript的包管理工具&#xff0c;npm。 在计算机中安装好Node.js之后&#xff0c;默认已经安装好了npm包管理工具&#xff0c;我们可以输入npm…

Java 深copy 浅copy 引用copy

大家好&#xff0c;我是烤鸭&#xff1a; 今天分享一下浅copy和深copy。 1. 深copy 什么是深copy&#xff0c;只复制原对象属性值&#xff0c;不管地址。 说一下业务场景&#xff1a; 如果我想创建一个对象&#xff0c;只是对原对象的某个属性值改变。普通的做法就是new 一个…

linux定时任务清理cache缓存

大家好&#xff0c;我是烤鸭&#xff1a; 如果你出现类似cache过多的情况&#xff0c;请参考这篇。 buff/cache 占了1.6G&#xff0c;多数情况下是无所谓的。但是有时候在系统内存不足的时候&#xff0c;可能会影响其他程序的执行。 之前就遇到过 jenkins 因为内存不足 集成失败…

SecureCRT Application 已停止工作

解决方法一&#xff1a; cmd ----> regedit —>HKEY_LOCAL_MACHINE\SOFTWARE\vandyke 删掉vandyke 解决方法二&#xff1a; SecureCRT使用过程中出现异常后自动关闭&#xff0c;导致下次无法正常启动&#xff08;运行程序无反应&#xff09;&#xff0c;此时一种可能的原…

SQLServer之事务简介

事务定义 事务是单个的工作单元。事务是在数据库上按照一定的逻辑顺序执行的任务序列&#xff0c;既可以由用户手动执行&#xff0c;也可以由某种数据库程序自动执行。 事务分类 自动提交事务 每条单独的语句都是一个事务。 在自动提交模式下&#xff0c; 每个数据库操作是在执…

Vmware centos无法连接网络

在vmware下安装了centos7&#xff0c;桥接模式&#xff0c;无法连接网络 解决方案一&#xff1a; 然后重启虚拟机 解决方案二&#xff1a; 然后再试试重启能否联网 解决方案三&#xff1a;

mybatis 一对一 一对多 级联查询

大家好&#xff0c;我是烤鸭&#xff1a; 今天分享一下关于mybatis的级联查询。 环境&#xff1a; mybatis 3.2.8 spring 4.1.9 1. 业务场景 在一个人申请某些账号或者权限的时候&#xff0c;比如微信的认证流程。 会让你一步一步按要求输入&#xff0c;比如第一步&am…

IDEA启动tomcat报错java.util.zip.ZipException: error in opening zip file

原因CATALINA_BASE参数后面多了一个斜杠 将&#xff1a;CATALINA_BASEK:\Tomcats\apache-tomcat-9.0.10_cform\ 改&#xff1a;CATALINA_BASEK:\Tomcats\apache-tomcat-9.0.10_cform

java 实现 常见排序算法(二) 插入排序

大家好&#xff0c;我是烤鸭&#xff1a; 今天分享一下基础排序算法之直接插入排序。 1. 直接插入排序&#xff1a; 原理&#xff1a;假设前面的数为有序数列&#xff0c;然后有序数列与无序数列的每个数比较&#xff0c;我们可以从右向左比较 思路&#xff1a;从第2…

linux 常用 启动命令 汇总

大家好&#xff0c;我是烤鸭&#xff1a; 没有准备启动脚本。服务器出问题之后&#xff0c;重启就是全部重启。 如&#xff1a; mysql,nginx,tomcat,zookeeper,rabbitmq,mongodb,redis,xxxxx 头大。持续更新。。。 consul启动&#xff1a; (公网可以访问 使用-client 0.0.0…

java 爬虫 抓取 网易云音乐

大家好&#xff0c;我是烤鸭&#xff1a; 今天和大家交流一下爬虫&#xff0c;抓取网易云音乐。只讨论技术&#xff0c;不提倡其他的。 1. 找音乐源地址 谷歌浏览器 F12 &#xff0c;找请求类型是 Media的。 2. 找请求链接 切换请求类型到 All&#xff0c;看 Respons…

idea警告Cannot resolve MVC View

关闭MVC View路径检查,Settings --> Editor -->Inspections -->搜索Spring MVC View—>取消勾选Spring MVC View Reference

ssh sftp 免密码 公钥登录

大家好&#xff0c;我是烤鸭&#xff1a; 今天分享的是java ssh sftp 免密码登录。 1. JAVA代码 ssh连接 http://www.360doc.com/content/14/0409/16/9552892_367544139.shtml https://blog.csdn.net/u013066244/article/details/70198839 公钥和私钥不需要用代码生成&…

CF989E A Trance of Nightfall(概率+矩阵快速幂优化+倍增)

CF传送门 洛谷传送门 【题目分析】 在zxy大佬的讲解下终于懂了这道题的做法了qwq。。。 首先根据题意&#xff0c;出发点不一定在特殊点上&#xff0c;但第一次操作后&#xff0c;之后所有的操作都是在特殊点上&#xff0c;所以先考虑从线上出发的最大概率&#xff0c;再加一步…