Role Object:
Person類別不再實作所有角色的介面,而改成內部使用一個集合來擺放可能的角色。
public class Person
{
private IList<PersonRole> _roles = new List<PersonRole>();
public string Name{get;set;}
public string Address{get;set;}
public string Tel{get;set;}
public void AddRole(PersonRole role)
{
_roles.Add(role);
}
public T RoleOf<T>() where T:PersonRole
{
foreach(PersonRole role in _roles)
{
if(role.HasType<T>())
{
return (T)role;
}
}
return null;
}
}
依據Matin Fowler大師的建議,替PersonRole加上HasType這個方法,日後我們的角色如果成長成一顆繼承樹時(Sequenal Roles),就會很有用。例如專任教師、科任教師的父角色都是教師,而教師的父角色可能是教職員工,這裏就可以寫些判斷的方法。public abstract class PersonRole
{
public bool HasType<T>()
{
if(this is T)
{
return true;
}
else
{
return false;
}
}
}
Customer與Employee就只要繼承PersonRole就好了public class Customer : PersonRole
{
public string DeliverAddress{get;set;}
}
public class Employee : PersonRole
{
public int MonthSalary{get;set;}
}
測試碼如下:[Test]
public void TestMakeCustomer()
{
Person person = new Person();
Customer customer = new Customer();
customer.DeliverAddress = "台北市忠孝東路";
person.AddRole(customer);
Customer customerRole = person.RoleOf<Customer>();
Assert.IsNotNull(customerRole);
Assert.AreEqual("台北市忠孝東路",customerRole.DeliverAddress);
}
[Test]
public void TestMakeEmployee()
{
Person person = new Person();
Employee employee = new Employee();
employee.MonthSalary = 40000;
person.AddRole(employee);
Employee employeeRole = person.RoleOf<Employee>();
Assert.IsNotNull(employeeRole);
Assert.AreEqual(40000,employeeRole.MonthSalary);
}

















