为什么不抽象工厂模式?
public class UserServiceFactory : IUserServiceFactory {
public EmployeeServiceFactory(IUserService employeeService
, IUserService managerService
, IUserService executiveService) {
//null guards
this.employeeService = employeeService;
this.managerService = managerService;
this.executiveService = executiveService;
}
}
从这里,您有 2 个选项,或者使用传统的 if-else 语句或策略模式来按对象类型解析。
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);
}
}
这听起来可能很复杂,但在你理解之后就足够简单了。