day07-09-建造者模式

Person

package day07.java8.pattern.builder;

import lombok.Data;

import java.util.Date;
/*
建造者模式:
Person.of().Name("zs").Ip("127.1.1").Age(18).Pwd("1234").build();
1、核心思想,将Person转成一个中间类Builder,然后构建builder,再返回Person对象
2、Person.of().Name("zs").Ip("127.1.1").Age(18).Pwd("1234").build();
Person.of()=》转成中间类Builder
Name("zs").Ip("127.1.1").Age(18).Pwd("1234")=>构建中间类
.build()=》 中间类转成person

 */

@Data
public class Person {
    private String name;
    private int age;
    private char sex;
    private String ip;
    private String pwd;
    private Date birthday;

    // 构造器,给Builder转成Person用的
    private Person(Builder builder){
        this.name =builder.name;
        this.age = builder.age;
        this.sex = builder.sex;
        this.ip = builder.ip;
        this.pwd = builder.pwd;
        this.birthday=builder.birthday;

    }
    // 将Person转成Builder
    // 这里用【转成】其实不太精确
    // 这里没有涉及到Person与Builder之间的转换
    // 这里单纯就是创建一个Builder。转换在后面的步骤
    public static Builder of() {
        Builder builder = new Builder();
        return builder;
    }

    // 静态内部类
    public static class Builder {
        private String name;
        private int age;
        private char sex;
        private String ip;
        private String pwd;
        private Date birthday;

        // 将当前的Builder转成Person
        public Person build() { // 创建person的方法
            return new Person(this);// 创建person,传入builder
        }

        // 成员变量,只生成set方法
        // 给Builder设置成员变量
        //然后返回当前的类Builder
        public Builder Name(String name) {
            this.name = name;
            return this;
        }

        public Builder Age(int age) {
            this.age = age;
            return this;
        }

        public Builder Sex(char sex) {
            this.sex = sex;
            return this;
        }

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

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

        public Builder Birthday(Date birthday) {
            this.birthday = birthday;
            return this;
        }
    }

    }

调用 

package day07.java8.pattern.builder;

public class TestPerson {
    public static void main(String[] args) {
        Person person = Person.of().Name("zs").Ip("127.1.1").Age(18).Pwd("1234").build();
        System.out.println("person = " + person);

    }
}

上一篇:Android APP开发08(AlertDialog)


下一篇:EF Core02