当前位置 > it书童 > java > 正文

建造者模式

java it书童 2020-12-26 17:29:44 0赞 0踩 88阅读 0评论

定义:将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示

适用场景:

  • 如果一个对象有非常复杂的内部结构(很多属性)

  • 想把复杂对象的创建和使用分离

示例:创建一门课程有诸多素材,如:视频、ppt、手记等,不强制每门课程都需要完整的素材,实例化课程时按需构建即可

@Data
public class Course {
    private String courseName;
    private String coursePPT;
    private String courseVideo;
    private String courseArticle;
    private String courseQA;

    public Course(CourseBuilder courseBuilder) {
        this.courseName = courseBuilder.courseName;
        this.coursePPT = courseBuilder.coursePPT;
        this.courseVideo = courseBuilder.courseVideo;
        this.courseArticle = courseBuilder.courseArticle;
        this.courseQA = courseBuilder.courseQA;
    }

    public static class CourseBuilder {
        private String courseName;
        private String coursePPT;
        private String courseVideo;
        private String courseArticle;
        private String courseQA;

        public CourseBuilder buildCourseName(String courseName) {
            this.courseName = courseName;
            return this;
        }
        public CourseBuilder buildCoursePPT(String coursePPT) {
            this.coursePPT = coursePPT;
            return this;
        }
        public CourseBuilder buildCourseVideo(String courseVideo) {
            this.courseVideo = courseVideo;
            return this;
        }
        public CourseBuilder buildCourseArticle(String courseArticle) {
            this.courseArticle = courseArticle;
            return this;
        }
        public CourseBuilder buildCourseQA(String courseQA) {
            this.courseQA = courseQA;
            return this;
        }

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

将构造者作为内部类,素材准备好后,再调用 build 生成最终的对象

public class Test {
    public static void main(String[] args) {
        // 按需调用,链式调用
        Course course = new Course.CourseBuilder()
            .buildCourseName("java设计模式精讲")
            .buildCoursePPT("java设计模式精讲PPT")
            .buildCourseVideo("java设计模式精讲视频")
            .build();
        System.out.println(course);
    }
}

jdk 例子:StringBuilder

@Override
public StringBuilder append(char c) {
    super.append(c);
    return this;
}

建造者模式在实际应用中很常见

关于我
一个文科出身的程序员,追求做个有趣的人,传播有价值的知识,微信公众号主要分享读书思考心得,不会有代码类文章,非程序员的同学请放心订阅
转载须注明出处:https://www.itshutong.com/articles/1007