设计模式-Java语言描述

2019-08-02-建造者模式

2019-08-02  本文已影响0人  王元

一,应用场景,

二,具体应用场景

三,简单实现代码如下

public final class Student {

    private Student(Builder b) {
        this.id = b.id;
        this.name = b.name;
    }

    private int id;
    private String name;

    public static class Builder {

        private int id;

        private String name;

        public Builder setId(int id) {
            this.id = id;
            return this;
        }

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

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

四,使用方式

Student stu = new Student.Builder().setId(0).setName("name").build()
上一篇 下一篇

猜你喜欢

热点阅读