设计模式-建造者模式

2021-07-13  本文已影响0人  东方欲晓_莫道君行早
建造者模式

建造者模式是将一个复杂对象的构建过程与它的表示分离,使得同样的构建过程可以创建不同的表示,属于创建型模式。
建造者模式的设计中主要有四个角色:

建造者模式的基本写法,以课程为例:
首先需要创建一个需要构造的产品类:


package com.jdwa.builder;

import lombok.Data;

@Data
public class Course {

    private String name;
    private String ppt;
    private String video;
    private String note;

    private String homework;

    @Override
    public String toString() {
        return "Course{" +
                "name='" + name + '\'' +
                ", ppt='" + ppt + '\'' +
                ", video='" + video + '\'' +
                ", note='" + note + '\'' +
                ", homework='" + homework + '\'' +
                '}';
    }
}

具体的建造者:

package com.jdwa.builder;

public class CourseBuilder {

    private Course course = new Course();

    public void addName(String name){
        course.setName(name);
    }

    public void addPPT(String ppt){
        course.setPpt(ppt);
    }

    public void addVideo(String video){
        course.setVideo(video);
    }

    public void addNote(String note){
        course.setNote(note);
    }

    public void addHomework(String homework){
        course.setHomework(homework);
    }

    public Course build(){
        return course;
    }

}

调用者:

package com.jdwa.builder;

public class Director {
    public static void main(String[] args) {
        CourseBuilder builder = new CourseBuilder();
        builder.addNote("【课堂笔记】");
        builder.addName("【设计模式】");
        builder.addHomework("【课后作业】");
        builder.addPPT("【PPT课件】");
        builder.addVideo("【回放视频】");

        System.out.println(builder.build());
    }
}

建造者模式的链式写法:

将建造者改造一下即可

package com.jdwa.builder;

/**
 * 可以先初始化一个或几个参数
 */
public class CourseBuilder2 {

    private Course course;

    public CourseBuilder2(String name){
        course = new Course();
        course.setName(name);
    }


    public CourseBuilder2 addPPT(String ppt){
        course.setPpt(ppt);
        return this;
    }

    public CourseBuilder2 addVideo(String video){
        course.setVideo(video);
        return this;
    }

    public CourseBuilder2 addNote(String note){
        course.setNote(note);
        return this;
    }

    public CourseBuilder2 addHomework(String homework){
        course.setHomework(homework);
        return this;
    }

    public Course build(){
        return course;
    }

}

调用者如下:

package com.jdwa.builder;

public class Director {
    public static void main(String[] args) {
        Course course = new CourseBuilder2("【设计模式】")
                .addNote("【课堂笔记】")
                .addHomework("【课后作业】")
                .addPPT("【PPT课件】")
                .addVideo("【回放视频】")
                .build();
        System.out.println(course);
    }
}

上一篇下一篇

猜你喜欢

热点阅读