遇到多个构造器参数(Constructor Parameters)时要考虑用构建器(Builder)
//营养素
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 {
// 必要参数
private final int servingSize;
private final int servings;
// 可选参数
private int calories = 0;
private int fat = 0;
private int carbohydrate = 0;
private int sodium = 0;
public Builder(int servingSize, int servings) {
this.servingSize = servingSize;
this.servings = servings;
}
public Builder calories(int calories) {
this.calories = calories;
return this;
}
public Builder sodium(int sodium) {
this.sodium = sodium;
return this;
}
public Builder fat(int fat) {
this.fat = fat;
return this;
}
public Builder carbohydrate(int carbohydrate) {
this.carbohydrate = carbohydrate;
return this;
}
//最后返回构建成功的对象
public NutritionFacts build() {
return new NutritionFacts(this);
}
}
//私有构造子
private NutritionFacts(Builder builder) {
this.servingSize = builder.servingSize;
this.servings = builder.servings;
this.calories = builder.calories;
this.fat = builder.fat;
this.sodium = builder.sodium;
this.carbohydrate = builder.carbohydrate;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "["+
"servingSize:"+servingSize+
",servings:"+servings+
",calories:"+calories+
",fat:"+fat+
",sodium:"+sodium+
",carbohydrate:"+carbohydrate+
"]";
}
public static void main(String [] args) {
NutritionFacts cocaCola = new NutritionFacts.Builder(240, 8)
.calories(100).sodium(35).carbohydrate(27).build();
System.out.println(cocaCola.toString());
}
}
输出结果:
[servingSize:240,servings:8,calories:100,fat:0,sodium:35,carbohydrate:27]
参考:http://www.cnblogs.com/xwdreamer/archive/2012/06/06/2538496.html
分享到:
相关推荐
易学设计模式,本书采用轻松诙谐的语气讲述了23种常用的设计模式,书籍格式为pdg格式
易学设计模式的随书光盘,源代码. 上手更容易
易学_设计模式_郭志学 易学_设计模式_郭志学
《Java易学设计模式》全书的随书源码,每一个章节一个压缩包,分别为:工厂模式、命令模式、组合模式、模板方法模式、工厂方法模式例子、状态模式例子、迭代器模式、解释器模式、享元模式、桥模式、装饰模式、代理...
《易学 设计模式》 郭志学 编著 随书源代码 ☆ 章节清单:☆ 第01章 欲速则不达:了解设计模式 第02章 磨刀不误砍柴工:UML语言概述 第03章 术业有专攻:简单工厂模式 (SimpleFactory) 第04章 精益求精:工厂方法...
易学设计模式源代码 很实用的。。。。。。。。。。
是《易学设计模式》一书的源码。用JAVA实现。拿出来与大家分享。
Java《易学设计模式》随书源代码,书中介绍了多种JAva模式的方法和使用,比如简单工厂模式、工厂方法模式例子、状态模式例子、迭代器模式、解释器模式、命令模式、模板方法模式、享元模式、桥模式、代理模式、适配器...
设计模式例子文档,简单易学。从中可以对各种模式有详细的了解
摘要:Java源码,书籍源码,随书源码,设计模式,Java电子书 运行环境:Java/Eclipse
C#设计模式之Decorator 装饰模式,pdf+视频教学,实例演示,易学易用~~
通过生动有趣的图解的方式,来展现每一个设计模式的原理,以及简单的实现案例,非常易学易懂,非常适合想要学习设计模式的童鞋。
资源比较大,只好分来传输,否则传不上去。设计模式中的经典书籍,强烈建议看这本书来学习设计模式。gof的设计模式太抽象了,这本书非常易学。
Java书籍 ,设计模式,搞笑版容易理解,学习简单,易学易用
设计模式之观察者模式,简单易学,便于理解。
该文档通过通俗易懂的描述外加代码实现的方式来讲述java的23中设计模式,简单易学。
java开发中的23种设计模式,内附各种模式实现的代码。简单易懂,轻松易学。
本代码时关于设计模式,可以直接使用的源代码,java程序编写。易懂易学,可以在实践中体会模式。
易学C++ , 大家慢慢下 易学C++ , 大家慢慢下 易学C++ , 大家慢慢下