大学大学, 大概学学 之 Null Object Pattern
时间:2011-06-03 来源:Chen.
最近在网上看到这个设计模式, 感觉很赞 :)
写代码的时候, 经常会遇到抛出NullReferenceException的情况, 举个最简单的例子:
public class Student
{
public void Method()
{
Console.WriteLine("Chen.");
}
}
public class Test
{
public static void Main(string[] args)
{
Student student = new Student();
student.Method(); //Chen.
student=null;
student.method(); //抛出NullReferenceException
}
}
Null Object Pattern可以很好地解决这一问题。
Null Object Pattern的作用就是让null值变为null object, 代码如下:
namespace DesignPatternTest.NullObject
{
public class Student
{
public Student() { }
public virtual bool IsNull
{
get { return false; }
}
public virtual void Method()
{
Console.WriteLine("Chen.");
}
}
}
namespace DesignPatternTest.NullObject
{
public class NullStudent : Student
{
private NullStudent() { }
public static NullStudent GetInstance()
{
return new NullStudent();
}
public override bool IsNull
{
get { return true; }
}
public override void Method()
{
//nothing
}
}
}
通过StudentManager管理:
namespace DesignPatternTest.NullObject
{
class StudentManager
{
private Student student=new Student();
public Student Student
{
set { student = value ?? NullStudent.GetInstance(); }
get { return student; }
}
}
}
对于Student类型的引用, 一旦为null值, 则指向NullStudent对象, 测试类如下:
namespace DesignPatternTest.NullObject
{
public class Test
{
public static void TestApp()
{
StudentManager m = new StudentManager();
Console.WriteLine(m.Student.IsNull); //false
m.Student.Method(); //Chen.
m.Student = null;
Console.WriteLine(m.Student.IsNull); //true
m.Student.Method(); //不会抛出NullReferenceException , 什么也不做
}
}
}
成功解决方法调用时的NullReferenceException问题。
相关阅读 更多 +