java 建造者模式

java 建造者模式


  • 应用场景
    • 一个类中构造器必传参数比较多,导致代码可读性比较差,容易出现bug
    • 一个类创建后,不需要再次修改属性的值
  • 建造者模式特点
    • 通过build()函数创建基本类,通过set 方式给构造函数赋值
    • 当构造函数参数比较多时,通过build() 和 set() 方法实现,代码结构逻辑清晰,代码精简
  • 代码展示: 代码实现了一个资源池创建
public class ResourcePoolConfig {

	private String poolName;

	private Integer maxTotal;

	private Integer maxIdle;

	private Integer minIdle;

	private ResourcePoolConfig(Builder builder) {
		this.poolName = builder.getPoolName();
		this.maxTotal = builder.getMaxTotal();
		this.maxIdle = builder.getMaxIdle();
		this.minIdle = builder.getMinIdle();
	}

	public String getPoolName() {
		return poolName;
	}

	public Integer getMaxTotal() {
		return maxTotal;
	}

	public Integer getMaxIdle() {
		return maxIdle;
	}

	public Integer getMinIdle() {
		return minIdle;
	}

	public static class Builder {
		
		private final static int DEFAULT_MAX_TOTAL = 100;

		private final static int DEFAULT_MAX_IDLE = 10;

		private final static int DEFAULT_MIN_IDLE = 5;

		private String poolName;

		private int maxTotal = DEFAULT_MAX_TOTAL;

		private int maxIdle = DEFAULT_MAX_IDLE;

		private int minIdle = DEFAULT_MIN_IDLE;

		public ResourcePoolConfig build() {
			return new ResourcePoolConfig(this);
		}

		public String getPoolName() {
			return poolName;
		}

		public Builder setPoolName(String poolName) {
			this.poolName = poolName;
			return this;
		}

		public Integer getMaxTotal() {
			return maxTotal;
		}

		public Builder setMaxTotal(Integer maxTotal) {
			this.maxTotal = maxTotal;
			return this;
		}

		public Integer getMaxIdle() {
			return maxIdle;
		}

		public Builder setMaxIdle(Integer maxIdle) {
			this.maxIdle = maxIdle;
			return this;
		}

		public Integer getMinIdle() {
			return minIdle;
		}

		public Builder setMinIdle(Integer minIdle) {
			this.minIdle = minIdle;
			return this;
		}

	}
}
/**
* 测试类
**/
public class Test {
	public static void main(String[] args) {
			ResourcePoolConfig config =
					new ResourcePoolConfig.Builder().setMaxIdle(15).setPoolName("mysql1").setMaxTotal(100).build();
			System.out.println(config.getMaxIdle());
			System.out.println(config.getPoolName());
			System.out.println(config.getMaxTotal());
		}
}

如果描述不全,请评论区指出,卤煮尽快更改,感谢!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值