一:类的创建和销毁__构建器builder和javaBean

本文探讨了如何解决静态工厂和构造函数在处理大量可选参数时的扩展问题,提出了使用JavaBean模式(通过无参构造函数及setter方法设置参数)和构建器Builder模式(适用于参数众多的情况)的解决方案。
摘要由CSDN通过智能技术生成

解决静态工厂和构造函数不能很好的扩展大量的可选参数,采用如下的两个方案解决

javaBean:

通过无参构造实例化一个对象,在调用setter方法来设定每一个必要/可选参数


构建器builder(只在很多参数才使用)

public class Student {
	// 必要参数
	private final int age;
	private final String sex;
	// 可选参数
	private final int tall;
	private final String name;

	// 构造函数
	private Student(Bulider bulider) {
		age = bulider.age;
		sex = bulider.sex;
		tall = bulider.tall;
		name = bulider.name;
	}

	/*
	 * 构建bulidre类
	 */
	public static class Bulider {
		// 必要参数
		private final int age;
		private final String sex;
		// 可选参数
		private int tall = 0;
		private String name = "";

		public Bulider(int age, String sex) {
			this.age = age;
			this.sex = sex;
		}

		/**
		 * 对可选参数进行构建
		 */
		public Bulider tall(int tall) {
			this.tall = tall;
			return this;
		}

		public Bulider name(String name) {
			this.name = name;
			return this;
		}

		// 返回构建的实例,关联student类
		public Student bulid() {
			return new Student(this);
		}
	}
}
使用:
Student student = new Student.Bulider(20, "男").bulid();
Student student = new Student.Bulider(20, "男").tall(150).bulid();


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值