Effective Java~2.Builder代替多参数Constructor

Builder模式

// Builder Pattern
public class NutritionFacts {private final int servingSize;private final int servings;private final int calories;private final int fat;private final int sodium;private final int carbohydrate;public static class Builder {// Required parametersprivate final int servingSize;private final int servings;// Optional parameters - initialized to default valuesprivate int calories = 0;private int fat = 0;private int sodium = 0;private int carbohydrate = 0;public Builder(int servingSize, int servings) {this.servingSize = servingSize;this.servings = servings;}public Builder calories(int val) {calories = val;return this;}public Builder fat(int val) {fat = val;return this;}public Builder sodium(int val) {sodium = val;return this;}public Builder carbohydrate(int val) {carbohydrate = val;return this;}public NutritionFacts build() {return new NutritionFacts(this);}}private NutritionFacts(Builder builder) {servingSize = builder.servingSize;servings = builder.servings;calories = builder.calories;fat = builder.fat;sodium = builder.sodium;carbohydrate = builder.carbohydrate;}
}

调用示例

NutritionFacts cocaCola = new NutritionFacts.Builder(240, 8).calories(100).sodium(35).carbohydrate(27).build();

Builder 模式非常适合类层次结构

// Builder pattern for class hierarchies
import java.util.EnumSet;
import java.util.Objects;
import java.util.Set;public abstract class Pizza {public enum Topping {HAM, MUSHROOM, ONION, PEPPER, SAUSAGE}final Set<Topping> toppings;abstract static class Builder<T extends Builder<T>> {EnumSet<Topping> toppings = EnumSet.noneOf(Topping.class);public T addTopping(Topping topping) {toppings.add(Objects.requireNonNull(topping));return self();}abstract Pizza build();// Subclasses must override this method to return "this"protected abstract T self();}Pizza(Builder<?> builder) {toppings = builder.toppings.clone(); // See Item 50}
}

这里有两个具体的 Pizza 的子类,其中一个代表标准的纽约风格的披萨,另一个是半圆形烤乳酪馅饼


import java.util.Objects;public class NyPizza extends Pizza {public enum Size { SMALL, MEDIUM, LARGE }private final Size size;public static class Builder extends Pizza.Builder<Builder> {private final Size size;public Builder(Size size) {this.size = Objects.requireNonNull(size);}@Override public NyPizza build() {return new NyPizza(this);}@Override protected Builder self() {return this;}}private NyPizza(Builder builder) {super(builder);size = builder.size;}
}public class Calzone extends Pizza {private final boolean sauceInside;public static class Builder extends Pizza.Builder<Builder> {private boolean sauceInside = false; // Defaultpublic Builder sauceInside() {sauceInside = true;return this;}@Override public Calzone build() {return new Calzone(this);}@Override protected Builder self() {return this;}}private Calzone(Builder builder) {super(builder);sauceInside = builder.sauceInside;}
}

调用示例

NyPizza pizza = new NyPizza.Builder(SMALL).addTopping(SAUSAGE).addTopping(ONION).build();Calzone calzone = new Calzone.Builder().addTopping(HAM).sauceInside().build();

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

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

相关文章

Alpine Linux 使用简介

From&#xff1a;https://www.aliyun.com/jiaocheng/137717.html Alpine Linux、CoreOS、RancherOS、Red Hat 原子项目、 VMware光子操作系统比较https://blog.csdn.net/hxpjava1/article/details/78482987 Alpine Linux配置使用技巧&#xff1a;https://www.aliyun.com/jiao…

实例学习SSIS(五)--理论介绍SSIS

导读&#xff1a; 实例学习SSIS&#xff08;一&#xff09;--制作一个简单的ETL包 实例学习SSIS&#xff08;二&#xff09;--使用迭代 实例学习SSIS&#xff08;三&#xff09;--使用包配置 实例学习SSIS&#xff08;四&#xff09;--使用日志记录和错误流重定向 实例学习SSIS…

MIT教授Tomaso Poggio演讲与专访:智能背后的科学与工程 | 腾讯AI Lab学术论坛

来源&#xff1a;腾讯AI实验室腾讯AI Lab第二届学术论坛在深圳举行&#xff0c;聚焦人工智能在医疗、游戏、多媒体内容、人机交互等四大领域的跨界研究与应用。全球30位顶级AI专家出席&#xff0c;对多项前沿研究成果进行了深入探讨与交流。腾讯AI Lab还宣布了2018三大核心战略…

linux捕捉信号sigint失败,为shell布置陷阱:trap捕捉信号方法论

本文目录&#xff1a;1.1 信号说明1.2 trap布置陷阱1.3 布置完美陷阱必备知识家里有老鼠&#xff0c;快消灭它&#xff01;哎&#xff0c;又给跑了。老鼠这小东西跑那么快&#xff0c;想直接直接消灭它还真不那么容易。于是&#xff0c;老鼠药、老鼠夹子或老鼠笼就派上用场了&a…

Effective Java~3. 私有Constructor 或Enum 强化单例

1、私有化构造器 // Singleton with static factory public class Elvis {private static final Elvis INSTANCE new Elvis();private Elvis() { ... }public static Elvis getInstance() { return INSTANCE; }public void leaveTheBuilding() { ... } } 可序列化对象单例&a…

VMware虚拟机软件

http://www.xuniji.com/vmware/ 虚拟机之家 http://www.ccw.com.cn/ 如何配置VMware虚拟机网络环境全程图解 nyytwngmail.com 8 转载于:https://www.cnblogs.com/hnytwn/archive/2009/10/28/1591044.html

linux 内置ssh,Linux ssh内置sftp配置说明

centos7 环境下已验证首先建立两个用户&#xff0c;用于sftp访问使用。eg:useradd -d /opt/sftp -s /bin/nologin sftp说明 -s /bin/nologin 禁止ssh登录服务器,其实如果将用户设置为用于sftp的话,不做此设置也是无法登录的会提示:This service allows sftp connections onl…

Trade Stages - The Trade Path

Gieno Trade Stages - The Trade Path STARTS OFF “greed orientated.”Loses because:1 Market problemsNot a zero sum game, a “very negative” sum gameMarket psychology – doing the wrong thing at the wrong timeThe majority is always wrongMarket exists on ch…

win10、oneplus7pro 使用 Kali

1、Windows 10 使用 Kali Linux子系统 微软为 Windows Subsystem for Linux (WSL) 带来了著名的 Kali Linux &#xff0c;无虚拟机&#xff0c;无Docker实现Windows 和 Kali Linux 交互。 window 开启 wsl 功能&#xff1a; 1.打开控制面板&#xff08; winR&#xff0c;输入…

Effective Java~9. try-with-resource 优先于 try-catch

try-finally 语句是保证资源正确关闭的最佳方式&#xff0c;但是当添加多个资源时&#xff0c;情况会变糟 // try-finally is ugly when used with more than one resource! static void copy(String src, String dst) throws IOException {InputStream in new FileInputStre…

linux安装汉语输入法,在linux中安装google拼音输入法

载自&#xff1a; 并修改了一些内容installhow to build and install scim-googlepinyin* Introduction* grab the source* build depends* runtime depends* build and installIntroductionThis document is intended to help you to build and install scim-googlepinyin fro…

干货|十大产业方向深度解析!《2020科技产业趋势报告》

来源&#xff1a;机器人大讲堂报告下载&#xff1a;https://pan.baidu.com/s/1BKf2rINXx0CVLhgokfYrgQ未来智能实验室是人工智能学家与科学院相关机构联合成立的人工智能&#xff0c;互联网和脑科学交叉研究机构。未来智能实验室的主要工作包括&#xff1a;建立AI智能系统智商评…

交互式数据包处理程序 Scapy 用法

From&#xff1a;https://www.cnblogs.com/hongxueyong/p/5641475.html Scapy 用法官方文档&#xff1a;http://scapy.readthedocs.io/en/latest/#starting-scapyAbout ScapyScapy is a Python program that enables the user to send, sniff and dissect and forge network pa…

top、postop、scrolltop、scrollHeight、offsetHeight

网页可见区域宽&#xff1a;document.body.clientWidth; 网页可见区域高&#xff1a;document.body.clientHeight; 网页可见区域高&#xff1a;document.body.offsetWeight: 网页可见区域高&#xff1a;document.body.offsetHeight; 网页正文全文宽&#xff1a;documen…

Effective Java~34. 用enum 代替 int 常量

在将枚举类型添加到该语言之前&#xff0c;表示枚举类型的常见模式是声明一组名为 int 的常量&#xff0c;每个类型的成员都有一个常量&#xff1a; // The int enum pattern - severely deficient! public static final int APPLE_FUJI 0; public static final int APPLE_…

linux 计算集群搭建,使用centos构建服务器计算集群

yum源的搭建排除列表#新建文件[rootcentos-test ~]# vim /usr/local/local_mirror/exclude.list#填入内容SRPMSaarch64ppc64ppc64ledebugrepodataEFILiveOSimagesisolinuxCentOS_BuildTagEULAGPLRPM-GPG-KEY-CentOS-7RPM-GPG-KEY-CentOS-Testing-7drpmsshell同步脚本#建立文件[…

展望2021年:智能机器人可监督工业机器人干活,效率提升30%

来源&#xff1a;极客网会帮我们吸地板、在公共场所担任导引员或是拆除炸弹的机器人呢可能感觉比较有趣&#xff0c;但那些负责组装汽车以及在工厂生产在线帮忙拾取物品的机器人&#xff0c;在整体价值上要高得多&#xff0c;而且也有越来越多的工/商业或消费性应用产品是由这种…

ASP。NET的设计思想

自从有了html与http&#xff0c;就有了浏览器与Web服务器&#xff0c;并有了Web应用&#xff0c;最初的交互模式是这样的&#xff1a; 该模式很好地运行了很多年。然而&#xff0c;随着计算机应用的发展&#xff0c;人们越来越不满足于只有静态内容的页面&#xff0c;而由某种机…

Kali linux 渗透测试技术之搭建WordPress Turnkey Linux及检测WordPress 应用程序漏洞

From&#xff1a;https://bbs.ichunqiu.com/thread-15716-1-1.html 怎样用 WPScan&#xff0c;Nmap 和 Nikto 扫描和检查一个 WordPress 站点的安全性&#xff1a;https://www.cnblogs.com/chayidiansec/p/7989274.html 为了收集用于测试的应用程序&#xff0c; Turnkey Linux…

AI芯片格局分布

来源&#xff1a;中国科学院自动化研究所 作者&#xff1a; 吴军宁如果说2016年3月份AlphaGo与李世石的那场人机大战只在科技界和围棋界产生较大影响的话&#xff0c;那么2017年5月其与排名第一的世界围棋冠军柯洁的对战则将人工智能技术推向了公众视野。阿尔法狗&#xff08;…