码迷,mamicode.com
首页 > 其他好文 > 详细

Builder模式的演示

时间:2019-12-22 18:12:39      阅读:77      评论:0      收藏:0      [点我收藏+]

标签:java   ide   image   演示   height   rri   str   file   turn   

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);
    }
}

Builder模式的演示

标签:java   ide   image   演示   height   rri   str   file   turn   

原文地址:https://www.cnblogs.com/mozq/p/12080360.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!