爲什麼不抽象工廠模式?
public class UserServiceFactory : IUserServiceFactory {
public EmployeeServiceFactory(IUserService employeeService
, IUserService managerService
, IUserService executiveService) {
//null guards
this.employeeService = employeeService;
this.managerService = managerService;
this.executiveService = executiveService;
}
}
從這裏,你有兩個選擇,要麼使用傳統的if-else語句或策略模式按對象類型來解決。
如果其他例子(內UserServiceFactory法):
public void DoSomething(User user) {
if (user is Employee) {
employeeService.DoSomething(user);
}
else if (user is Manager) {
managerService.DoSomething(user);
}
else if (user is Executive) {
executiveService.DoSomething(user);
}
}
解決按對象類型:
public void DoSomething(Employee user) {
employeeService.DoSomething(user);
}
public void DoSomething(Manager user) {
managerService.DoSomething(user);
}
public void DoSomething(Executive user) {
executiveService.DoSomething(user);
}
應該有另一種方式來做到這一點,通過使用命名了配置,但我仍然無法做到這一點。
中直接調用用法:
public void CallUser() {
// declare the services and user here
UserServiceFactory userServiceFactory = new UserServiceFactory(employeeService
, managerService
, executiveService);
userServiceFactory.DoSomething(user);
}
其他服務用法,注射工廠,而不是服務集合。
public class UserServiceConsumer:IUserServiceConsumer {
public UserServiceConsumer(IUserServiceFactory userServiceFactory) {
this.userServiceFactory = userServiceFactory;
}
IUserServiceFactory userServiceFactory;
public void ConsumeFactory(User user) {
//do some validation maybe
userServiceFactory.DoSomething(user);
}
}
聽起來很複雜,但在你理解後很簡單。
我認爲這是正確的軌道。對於ServiceResolver.Current.Resolve>()有沒有辦法解決而不通過T?我沒有定義T泛型,只是對象類型。 –
NullReference
2013-04-23 19:44:43
Gahh ...不是我想聽的.... – Aron 2013-04-24 01:15:23