CS-Notes/notes/设计模式 - 空对象.md
2019-11-02 22:11:39 +08:00

63 lines
1.4 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

## 空对象Null
### Intent
使用什么都不做
的空对象来代替 NULL
一个方法返回 NULL意味着方法的调用端需要去检查返回值是否是 NULL这么做会导致非常多的冗余的检查代码并且如果某一个调用端忘记了做这个检查返回值而直接使用返回的对象那么就有可能抛出空指针异常
### Class Diagram
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/22870bbe-898f-4c17-a31a-d7c5ee5d1c10.png"/> </div><br>
### Implementation
```java
public abstract class AbstractOperation {
abstract void request();
}
```
```java
public class RealOperation extends AbstractOperation {
@Override
void request() {
System.out.println("do something");
}
}
```
```java
public class NullOperation extends AbstractOperation{
@Override
void request() {
// do nothing
}
}
```
```java
public class Client {
public static void main(String[] args) {
AbstractOperation abstractOperation = func(-1);
abstractOperation.request();
}
public static AbstractOperation func(int para) {
if (para < 0) {
return new NullOperation();
}
return new RealOperation();
}
}
```
<div align="center"><img width="320px" src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/githubio/公众号二维码-2.png"></img></div>