态度决定高度、企图决定版图、格局决定结局

导航

尝试下NullObject模式

using System;
using System.Collections;

public class DB
{
private static ArrayList list = new ArrayList();
public static void AddEmp(string name)
{
list.Add(new Employee(name));
}
public static IEmployee SearcheEmployee(string empName)
{
IEmployee emptemp = NullEmployee.GetInstance();
foreach(Employee emp in list)
{
if (emp.Name == empName)
{
emptemp = emp;
}
}
return emptemp;
}
}

public interface IEmployee
{
void SayHello();
}

 

//结合了Singleton

public class NullEmployee:IEmployee
{
private static NullEmployee emp;
private NullEmployee(){}
public static NullEmployee GetInstance()
{
if(emp==null)
emp = new NullEmployee();
return emp;
}
public void SayHello()
{
Console.WriteLine("Null Employee !");
}
}

public class Employee:IEmployee
{
public Employee(string n)
{
name = n;
}
private string name ;
public string Name
{
get
{
return name;
}
}
public void SayHello()
{
Console.WriteLine("Hello!"+name);
}
public override string ToString()
{
return "The Employee Name is :"+name;
}
}

public class MyClass
{
public static void Main()
{
DB.AddEmp("Randy");
DB.AddEmp("Edward");
DB.AddEmp("Flying");
Console.WriteLine(DB.SearcheEmployee("Edward").ToString());
Console.WriteLine(DB.SearcheEmployee("Fei").ToString());
DB.SearcheEmployee("Fei").SayHello();
Console.Read();
}
}

posted on 2007-01-02 21:29  flyingchen  阅读(435)  评论(0编辑  收藏  举报