首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件开发 >

易学设计形式五 建造模式(Builder)

2012-11-04 
易学设计模式五 建造模式(Builder)遇到多个构造器参数(Constructor Parameters)时要考虑用构建器(Builder)

易学设计模式五 建造模式(Builder)
遇到多个构造器参数(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

热点排行