空对象模式(Null Object Pattern)
Null Object Pattern,一个空对象取代 NULL 对象实例的检查。Null 对象不是检查空值,而是反应一个不做任何动作的关系。这样的 Null 对象也可以在数据不可用的时候提供默认的行为。
| package com.xxx; |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| public abstract class AbstractUser { |
| protected String name; |
| |
| |
| |
| |
| |
| public abstract boolean isNil(); |
| |
| |
| |
| |
| |
| public abstract String getName(); |
| } |
| |
| package com.xxx; |
| |
| import com.qf.AbstractCustomer; |
| |
| |
| |
| public class RealUser extends AbstractUser { |
| |
| public RealUser(String name){ |
| this.name = name; |
| } |
| @Override |
| public boolean isNil() { |
| return false; |
| } |
| |
| @Override |
| public String getName() { |
| return name; |
| } |
| } |
| package com.xxx; |
| |
| import com.qf.AbstractCustomer; |
| |
| |
| |
| public class NullUser extends AbstractUser { |
| @Override |
| public boolean isNil() { |
| return true; |
| } |
| |
| @Override |
| public String getName() { |
| return "空"; |
| } |
| } |
| |
| package com.xxx; |
| |
| |
| |
| |
| public class UserFactory { |
| public static final String[] names = {"张三", "李四", "王五"}; |
| |
| public static AbstractUser getUser(String name){ |
| for (int i = 0; i < names.length; i++) { |
| if (names[i].equalsIgnoreCase(name)) { |
| return new RealUser(name); |
| } |
| } return new NullUser(); |
| } |
| } |
| |
| package com.xxx; |
| |
| |
| |
| public class Test { |
| public static void main(String[] args) { |
| AbstractUser lisi = UserFactory.getUser("李四"); |
| AbstractUser lufei = UserFactory.getUser("路飞"); |
| |
| System.out.println(lisi.getName()); |
| System.out.println(lufei.getName()); |
| } |
| } |
本文作者:Ritchie里其
本文链接:https://www.cnblogs.com/wang-zeyu/p/17070087.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步