รูปแบบอ็อบเจกต์ null ช่วยให้เราเขียนโค้ดที่สะอาดเพื่อหลีกเลี่ยงการตรวจสอบค่า null ที่ทำได้ การใช้รูปแบบอ็อบเจกต์ 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() {
}
}