首页 > 代码库 > 设计模式之空对象(Null Object)模式

设计模式之空对象(Null Object)模式

通过引用Null Object,用于取消业务逻辑中对对象的为空判断


类图:




Nullable:

package com.demo.user;

public interface Nullable {
	boolean isNull();
}


Group:

package com.demo.user;

public class Group implements Nullable{
	private int groupId;
	private String groupName;
	public int getGroupId() {
		return groupId;
	}
	public void setGroupId(int groupId) {
		this.groupId = groupId;
	}
	public String getGroupName() {
		return groupName;
	}
	public void setGroupName(String groupName) {
		this.groupName = groupName;
	}
	public boolean isNull() {
		return true;
	}
	
}


NullGroup:

package com.demo.user;

public class NullGroup extends Group {
	
	private NullGroup() {
	}

	@Override
	public int getGroupId() {
		return 9999999;
	}
	@Override
	public boolean isNull() {
		return false;
	}
	static Group createNull(){
		return new NullGroup();
	}
}


User:

package com.demo.user;

public class User {
	private int userId ;
	private String userName;
	private Group group;
	
	public int getUserId() {
		return userId;
	}
	public void setUserId(int userId) {
		this.userId = userId;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public Group getGroup() {
		//判断返回一个NullGroup对象
		return group==null?NullGroup.createNull():group;
	}
	public void setGroup(Group group) {
		this.group = group;
	}
	
}


UserService:

package com.demo.user;

public class UserService {
	public void add(User user){
		//获取groupId
		int  groupId=user.getGroup().getGroupId();
		//doing something
	}
}





设计模式之空对象(Null Object)模式