创建对象之构建器

适用情况:
当对象属性比较多时使用构造器或者静态工厂方法创建对象时会比较复杂所以采用构建器的方式动态扩展属性
主要用于解决对象部分的变化需求
package com.liangliang.coreJava.OOP.builder;
/**
* 构建器builder模式
* @author sunliangliang
* 适用于参数比较多的类
/
public class Lunch {
private String cake;
private String meat;
private String milk;
private String drink;
/
*
* static修饰类主要用于匿名内部类
* @author sunliangliang
*/
public static class Builder{
private String meat;//必填项
private String cake;
private String milk;
private String drink;

        public Builder(String meat){
            this.meat=meat;
        }
        public Builder addCake(String cake){
            this.cake=cake;
            return this;
        }
        public Builder addMilk(String milk){
            this.milk = milk;
            return this;
        }
        public Builder addDrink(String drink){
            this.drink = drink;
            return this;
        }
        public Lunch create(){
            return new Lunch(this);
        }
        
    }
    private Lunch(Builder bulider){
        this.meat=bulider.meat;
        this.cake=bulider.cake;
        this.milk=bulider.milk;
        this.drink=bulider.drink;
    }
    
    @Override
    public String toString() {
        return "Lunch [cake=" + cake + ", meat=" + meat + ", milk=" + milk + ", drink=" + drink + "]";
    }

    public static void main(String[] args) {
        Lunch.Builder builder=new Lunch.Builder("meat");
        Lunch lunch=builder.addCake("cake").addMilk("milk").create();
        System.out.println(lunch.toString());
    
    }
}

你可能感兴趣的:(创建对象之构建器)