首页 > 代码库 > 设计模式之空对象(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)模式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。