设计模式-建造者模式

117 阅读1分钟

建造者模式

创建对象时经常会使用到的设计模式,lombok插件也帮开发者实现了建造者模式的注解@Builder,@SuperBuilder, 挺简单,就像造东西一样,无所谓顺序,想怎么造怎么造,但是造出来的都是一样的实例,想做个独臂无头的机器人也可以,什么都有的机器人也可以。组合任由开发者选择,往小了说搞个对象,往大了说可以搞个大的组合服务。

Robot

public class Robot {
    private String head;
    private String hand;
    private String foot;

    public String getHead() {
        return head;
    }

    public String getHand() {
        return hand;
    }

    public String getFoot() {
        return foot;
    }

    public String getBody() {
        return body;
    }

    private String body;
    private Robot(String head, String hand, String foot, String body){
        this.head = head;
        this.hand = hand;
        this.foot = foot;
        this.body = body;
    }

    public static Robot.RobotBuilder builder(){
        return new RobotBuilder();
    }

    public static class RobotBuilder{
        private String head;
        private String hand;
        private String foot;
        private String body;

        public Robot build(){
            return new Robot(this.head, this.hand, this.foot, this.body);
        }

        public Robot.RobotBuilder head(String head){
            this.head = head;
            return this;
        }

        public Robot.RobotBuilder hand(String hand){
            this.hand = hand;
            return this;
        }

        public Robot.RobotBuilder foot(String foot){
            this.foot = foot;
            return this;
        }

        public Robot.RobotBuilder body(String body){
            this.body = body;
            return this;
        }
    }
}

创建一个Robot

public class TestRobot {
    public static void main(String[] args){
        Robot myRobot = Robot.builder().body("body").head("head").foot("foot").build();
        System.out.println(myRobot.getBody());
        System.out.println(myRobot.getHead());
        System.out.println(myRobot.getFoot());
        System.out.println(myRobot.getHand());
    }
}
print:

body
head
foot
null