null 객체 패턴은 가능한 경우 null 검사를 피하는 깨끗한 코드를 작성하는 데 도움이 됩니다. 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() {
}
}