Builder模式的演示

Builder模式的演示

package com.mozq.mb.mb01.pojo;

/*
   类的某些参数给出了默认值,但是一旦设置了就不可变。使用Builder模式来创建。
 */
public class ImageConfig {
    private final int x;
    private final int y;
    private final int width;
    private final int height;
    private final String fileDiskPath;

    public ImageConfig(Builder builder){
        this.x = builder.x;
        this.y = builder.y;
        this.width = builder.width;
        this.height = builder.height;
        this.fileDiskPath = builder.fileDiskPath;
    }

    public static class Builder {
        private int x = 0;
        private int y = 0;
        private int width = 0;
        private int height = 0;
        private String fileDiskPath = "";
        public Builder(){}
        public Builder(int x, int y, int width, int height, String fileDiskPath){
            this.x = x;
            this.y = y;
            this.width = width;
            this.height = height;
            this.fileDiskPath = fileDiskPath;
        }
        public Builder x(int x){
            this.x = x;
            return this;
        }
        public Builder y(int y){
            this.y = y;
            return this;
        }
        public Builder width(int width){
            this.width = width;
            return this;
        }
        public Builder height(int height){
            this.height = height;
            return this;
        }
        public Builder fileDiskPath(String fileDiskPath){
            this.fileDiskPath = fileDiskPath;
            return this;
        }
        public ImageConfig build(){
            return new ImageConfig(this);
        }
    }

    @Override
    public String toString() {
        return "ImageConfig{" +
                "x=" + x +
                ", y=" + y +
                ", width=" + width +
                ", height=" + height +
                ", fileDiskPath='" + fileDiskPath + '\'' +
                '}';
    }

    public static void main(String[] args) {
        ImageConfig imageConfig = new ImageConfig.Builder().x(200).build();
        System.out.println(imageConfig);
    }
}
posted @ 2019-12-22 17:23  没有理由不会呀  阅读(150)  评论(0编辑  收藏  举报