2019-11-02 22:11:39 +08:00
|
|
|
|
## 空对象(Null)
|
|
|
|
|
|
|
|
|
|
### Intent
|
|
|
|
|
|
|
|
|
|
使用什么都不做
|
|
|
|
|
|
|
|
|
|
的空对象来代替 NULL。
|
|
|
|
|
|
|
|
|
|
一个方法返回 NULL,意味着方法的调用端需要去检查返回值是否是 NULL,这么做会导致非常多的冗余的检查代码。并且如果某一个调用端忘记了做这个检查返回值,而直接使用返回的对象,那么就有可能抛出空指针异常。
|
|
|
|
|
|
|
|
|
|
### Class Diagram
|
|
|
|
|
|
2019-12-06 10:11:23 +08:00
|
|
|
|
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/22870bbe-898f-4c17-a31a-d7c5ee5d1c10.png"/> </div><br>
|
2019-11-02 22:11:39 +08:00
|
|
|
|
|
|
|
|
|
### 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>
|