如何用 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() {
   }
}

更新於: 2020 年 11 月 25 日

126 次瀏覽

開啟您的 職業生涯

完成課程並取得認證

開始學習
廣告
© . All rights reserved.