现在的位置: 首页 > 综合 > 正文

effective java之 builder模式

2014年03月15日 ⁄ 综合 ⁄ 共 2115字 ⁄ 字号 评论关闭

在java开发中我们经常需要创建对象 ,我们常用的创建对象的方法有两种 
1  使用构造器来创建对象 如果有多个可变参数 ,就需要写多个构造方法,这种方法在遇到多个参数时不好控制

2. javabean的写法,私有化成员变量, 私有构造方法 ,通过setter和getter来设置和获取值 ,这种构造的缺点是传入的参数不好检测,例如有些非空的数据等

3.静态工厂
现在我们介绍的builder模式创建的对象 适用于有多个可变参数和一定数量的限制参数的时候

贴代码

public class Student {
	private int id;
	private int classId;
	private int schoolId;
	private String name;
	private String className;
	private String schoolName;
	private String sex;
	private String age;

	public static class Builder {
		// 非空信息,限定值(必须填的)
		private int id;
		private int classId;
		private int schoolId;
		// 选择信息,可以不填的,不填默认为“未设定”
		private String name = "未设定";
		private String className = "未设定";
		private String schoolName = "未设定";
		private String sex = "未设定";
		private String age = "未设定";

		//builder构造方法 必须设置限定属性的值
		public Builder(int id, int classId, int schoolId) {
			this.id = id;
			this.classId = classId;
			this.schoolId = schoolId;
		}

		//外部提供的设置可选属性的值
		public Builder name(String name) {
			this.name = name;
			return this;
		}

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

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

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

		public Builder age(String age) {
			this.age = age;
			return this;
		}
		
		public Student build(){
			return new Student(this);
		}

	}

	//私有化构造方法 外部不能直接new student
	private Student(Builder builder) {
		//通过赋值这种方法来检测传入的值得正确性 不正确会抛出异常
		this.id = builder.id;
		this.classId = builder.classId;
		this.schoolId = builder.schoolId;
		this.name = builder.name;
		this.className = builder.className;
		this.schoolName = builder.schoolName;
		this.age = builder.age;
		this.sex = builder.sex;
	}

	//提供访问对象各项属性数据的接口
	public int getId() {
		return id;
	}

	public int getClassId() {
		return classId;
	}

	public int getSchoolId() {
		return schoolId;
	}

	public String getName() {
		return name;
	}

	public String getClassName() {
		return className;
	}

	public String getSchoolName() {
		return schoolName;
	}

	public String getSex() {
		return sex;
	}

	public String getAge() {
		return age;
	}

}

逻辑控制层
public class Controler {
	public static void main(String[] args) {
		Student student = new Student.Builder(2012, 10086, 13800).name("罗康").age("20").sex("男")
				.build();
		System.out.println("名字:" + student.getName() + " - 学校名:" + student.getSchoolName()
				+ " - 性别:" + student.getSex());
	}
}

优点在于 编写简单  在对象域检测参数的合法性 传入参数方便 。我第一次见这种写法是在开发android软件时使用new AlertDialog.builder(Context context).setTitle(" ").create().show(); 


抱歉!评论已关闭.