空对象模式可以帮助我们编写干净的代码,从而尽可能避免空检查。使用空对象模式,调用者不必关心它们是空对象还是真实对象。不可能在每种情况下都实现空对象模式。有时,它很可能返回空引用并执行一些空检查。
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() { } }