如何用 C# 實現 Null 物件模式?
空物件模式有助於我們在儘量避免需要對 null 值進行檢查的情況下編寫簡潔程式碼。使用空物件模式時,呼叫者無需關心響應中是空物件還是實際物件。無法在所有場景下實現空物件模式。有時,可能會返回一個 null 引用並執行一些空值檢查。
示例
static class Program{
static void Main(string[] args){
Console.ReadLine();
}
public static IShape GetMobileByName(string mobileName){
IShape mobile = NullShape.Instance;
switch (mobileName){
case "square":
mobile = new Square();
break;
case "rectangle":
mobile = new Rectangle();
break;
}
return mobile;
}
}
public interface IShape {
void Draw();
}
public class Square : IShape {
public void Draw() {
throw new NotImplementedException();
}
}
public class Rectangle : IShape {
public void Draw() {
throw new NotImplementedException();
}
}
public class NullShape : IShape {
private static NullShape _instance;
private NullShape(){ }
public static NullShape Instance {
get {
if (_instance == null)
return new NullShape();
return _instance;
}
}
public void Draw() {
}
}
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP