码迷,mamicode.com
首页 > 其他好文 > 详细

Builder 模式

时间:2016-08-05 19:21:47      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

package cn.zno.common;

public class Car {
    private String brand;
    private String type;
    private String color;

    public static class Builder {
        // 必填
        private String brand;
        // 选填
        private String type = "SUV";
        private String color = "black";

        public Builder(String brand) {
            this.brand = brand;
        }

        public Builder type(String type) {
            this.type = type;
            return this;
        }

        public Builder color(String color) {
            this.color = color;
            return this;
        }

        public Car build() {
            return new Car(this);
        }
    }

    /**
     * Builder 模式
     * 不提供构造器
     * */
    private Car(Car.Builder builder) {
        this.brand = builder.brand;
        this.type = builder.type;
        this.color = builder.color;
    }

    @Override
    public String toString() {
        return "Car [brand=" + brand + ", type=" + type + ", color=" + color + "]";
    }

}

 

package lianxi;

import org.junit.Test;

import cn.zno.common.Car;
import cn.zno.common.Car.Builder;

public class CarTest {
    @Test
    public void f1() {
        Builder carBuilder = new Car.Builder("Benz");
        Car car = carBuilder.build();
        System.out.println(car);
    }

    @Test
    public void f2() {
        Builder carBuilder = new Car.Builder("Ford").type("Pickup").color("Red");
        Car car = carBuilder.build();
        System.out.println(car);
    }
}

 

Car [brand=Benz, type=SUV, color=black]
Car [brand=Ford, type=Pickup, color=Red]

 

Builder 模式

标签:

原文地址:http://www.cnblogs.com/zno2/p/5470452.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!