设计模式之空对象(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
}
}
上一篇:判断字符串中是否包含Emoji表情代码


下一篇:sql点滴37—mysql中的错误Data too long for column '' at row 1