• 设计模式之空对象(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
    	}
    }
    





  • 相关阅读:
    sh_02_判断年龄改进版
    面向对象-内置函数和内置方法
    python面向对象-三大特性
    面向对象编程
    面向对象编程-回合制游戏
    练习Dream-购物车
    bytes和str的区别与转换
    字符串的操作和使用方法。
    程序员必须掌握的600个单词
    移动端的网页设计流程有哪些?
  • 原文地址:https://www.cnblogs.com/zfyouxi/p/4482817.html
Copyright © 2020-2023  润新知