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