Java底层安全实体类

package com.mytest.test;

import java.io.Serializable;

public class Student 
implements Cloneable,Serializable{

	private static final long serialVersionUID = 8368233614316145887L;
	
	private final String name;
	
	private final String age;
	
	private transient final int hight;
	
	private Student(String name,String age,int hight){
		this.age = age;
		this.name = name;
		this.hight = hight;
	}
	
	public Student(){
		throw new RuntimeException("can't creat no reference Student");
	}
	
	private Student(History history) {
		name = history.name;
		age = history.age;
		hight = history.hight;
	}

	static Student creatStudent(String name,String age,int hight){
		if (hight < 0) 
			throw new RuntimeException(" hight can't less than 0 ");		
		
		if (Integer.valueOf(age) < 0) 
			throw new RuntimeException(" age can't less than 0 ");	
		
		//name = new String(name.getBytes("utf-8"));		
		return new Student(name,age,hight);
	}
	
	String getName() {
		return name;
	}

	String getAge() {
		return age;
	}
	
	int getHight() {
		return hight;
	}

	@Override
	public String toString() {
		return "姓名 -- "+name+" 年龄 -- "+age+" 身高 -- "+hight;
	}
	
	static class History{
		
		private final String name;
		
		private final String age;
		
		private int hight;
		
		public History(String name,String age){
			this.name = name;
			this.age = age;
		}
		
		public History hight(int hight){
			this.hight = hight;
			return this;
		}
		
		public Student build(){
			return new Student(this);
		}
	}
	
	@Override
	Object clone() throws CloneNotSupportedException{		
		return super.clone();		
	}
	
	static Student safeInstance(Student student){
		if (student.getClass() != Student.class)
			return creatStudent(student.getName(), student.getAge(), student.getHight());		
		return student;
	}
}

知识点:对象一旦生成,不会被改变,保证在使用中的安全。
当多个地方都用到了着同一个对象,不会因为一个地方对该对象进行操作,而使另一处的使用出现问题。
get方法并非必须的。而是可以提供一些工具方法。初始化对象,调用工具方法来完成某些功能。该对象将作为
常驻对象,持续稳定的为系统服务。

你可能感兴趣的:(小技术点)