Builder模式的演示
Posted mozq
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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);
}
}
以上是关于Builder模式的演示的主要内容,如果未能解决你的问题,请参考以下文章
Java设计模式Builder建造者模式,Builder设计模式简单代码示例