zoukankan      html  css  js  c++  java
  • 设计模式之空对象(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
    	}
    }
    





  • 相关阅读:
    重启Linux机器异常的解决方法
    SSH连接Linux服务器异常
    H5本地存储
    Spring MVC概述
    Linux下oracle开机自启动
    [ASP.NET MVC]@Partial 和@RenderPartial的区别
    [ASP.NET MVC]EntityFramework离线部署
    [ASP.NET MVC]@RenderSection,@RenderBody(),@RenderPage
    [ASP.NET MVC]@Html.AntiForgeryToken() 防止CSRF攻击
    [ASP.NET MVC]@Scripts.Render、@Styles.Render的使用
  • 原文地址:https://www.cnblogs.com/zfyouxi/p/4482817.html
Copyright © 2011-2022 走看看