如何在C#中实现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() {
}
}热门推荐
10 描写周末的祝福语简短
11 婚礼结束聚餐祝福语简短
12 八一幼儿祝福语大全简短
13 回家长的祝福语简短
14 简短祝福语大全暖心
15 祝福语诗意文案简短
16 最真的新春祝福语简短
17 女朋友考试祝福语简短
18 男童毕业蛋糕祝福语简短