14.8空对象(一)

尽可能的避免空指针异常:

    想要达到:即使对象是空值,依然可以响应对象的所有信息,你仍需要某种方式去测试其是否为空

解决方案:

public interface Null {}

这样可以使用instanceof 探测空对象,省去isNull()方法

 *使用默认权限使用包外无法使用,关闭包外继承
 *
 */
 class Person {
	//从技术的角度来说,不可变类是允许公有域的,虽然这样不太好
	public final String first;
	public final String last;
	public final String address;
	
	//实例化必需赋值
	public Person(String first, String last, String address) {
		super();
		this.first = first;
		this.last = last;
		this.address = address;
	}
	
	
	@Override
	public String toString() {
		return "Person [first=" + first + ", last=" + last + ", address=" + address + "]";
	}
	
	//嵌套类 使用static 修饰关闭与外围类的关联,相对独立存在 
	public static class NullPerson extends Person implements Null{
		
		private NullPerson() {
			super("None","None","None");
		}
		
		public String toString() {
			return "NullPerson";
		}
		
	}
	
	//单例模式
	public static final Person NULL = new NullPerson();
}

通常,空对象都是单例,注意,此对象为不可变对象,这个对象里面的值是没胡办法修改的,它的空值是可以用instanceof 来探测的 ,

为什么使用单例:

可以使用equals()甚至==来与Person.NULL来进行比较

public class Position {
	private String title;
	private Person person;
	public Position(String jobTitle, Person employee) {
		super();
		title = jobTitle;
		person = employee;
		if(person == null) 
			person = Person.NULL;
	}
	
	public Position(String jobTitle) {
		super();
		title = jobTitle;
		person = Person.NULL;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public Person getPerson() {
		return person;
	}

	public void setPerson(Person person) {
		if(person == null) 
			person = Person.NULL;
	}

	@Override
	public String toString() {
		return "Position [title=" + title + ", person=" + person + "]";
	}
	
}

如何代表空职位:

就是Person.NULL,需要Position的空对象,但是你不需要申明它 PS:极限编程的原则之一:做可以工作的最简单的事情

public class Staff extends ArrayList<Position>{
	public void add(String title,Person person) {
		add(new Position(title, person));
	}
	
	public void add(String... titles) {
		for(String title:titles) {
			add(new Position(title));
		}
	}

	public Staff(String... titles) {
		add(titles);
	}
	
	public boolean positionAvailable(String title) {
		for(Position position:this) {
			if(position.getTitle().equals(title) && position.getPerson() == Person.NULL)
				return true;
		}
		return false;
	}
	
	public void fillPosition(String title,Person person) {
		forEach(position->{
			if(position.getTitle().equals(title) && position.getPerson() == Person.NULL)
				position.setPerson(person);
			return;
		});
	}
	
}

或许到这里,你依然需要测试空对象,这与检查null没胡差异,但是在其它地地方,你就不必执行额外的测试,可以直接假设所的对象都是有效的

猜你喜欢

转载自blog.csdn.net/perfect_red/article/details/80589276
今日推荐