【发布时间】:2015-04-28 07:10:13
【问题描述】:
上下文:
我有一个 REST 服务,比如说 CustomerService,它现在有一个方法 getCustomer(id, country)。现在的要求是,根据国家/地区,我必须执行不同的业务逻辑,例如访问不同的数据库或一些自定义规则,然后报告我收到了这样的请求。
首先根据国家/地区解决不同的实现,我使用了工厂模式,如下所示:
所有国家/地区实施的通用界面
public Interface CustomerServiceHandler{
Cusomer getCustomer(String id, String country);
}
然后工厂为
public class CustomerServiceHandlerFactory{
public CustomerServiceHandler getHandler(String country){...};
}
使用 Facade 的实现细节
注意这个外观是从 REST 类调用的,即CustomerService
public CustomerServiceFacade{
public Customer getCustomer(String id, String country){
//use factory to get handler and then handler.getCustomer
Customer customer = factory.getHandler(country).getCustomer(id,country);
//report the request
reportingService.report('fetch-customer',....);
return customer;
}
}
按照 SRP(单一职责原则),这个门面没有实现单一目标。它正在接受客户并报告已收到此类请求。所以我想到了装饰器模式如下。
使用装饰器模式实现:
//this is called from Rest layer
public ReportingCustomerHandler implements CustomerServiceHandler{
//this delegate is basically the default implementation and has factory too
private CustomerServiceHandler delegate;
private ReportingService reporting;
public Customer getCustomer(String id, String country){
Customer customer = delegate.getCustomer(id, country);
reporting.report(....);
return customer;
}
}
//this is called from ReportingCustomerHandler
public DefaultCustomerServiceHandler implements CustomerServiceHandler{
private CustomerServiceHandlerFactory factory;
public Customer getCustomer(String id, String country){
//get factory object else use itself, even default implementation is provided by factory
CustomerServiceHandler handler = factory.getHandler(country);
return handler.getCustomer(id,country);
}
}
注意:在第二种方法中,我也将接口CustomerServiceHandler(显示在工厂代码中)用于Reporting and Default implementations。
那么正确的方法是什么,或者如果存在更合适的方法,还有什么替代方法。
问题的第二部分
如果我必须维护两个不同的接口,即一个 CustomerServiceHandler 来实现不同国家/地区的实现,一个用于服务 REST 层,该怎么办。那么什么可以是设计或替代方案。在这种情况下,我认为外观会合适。
【问题讨论】:
标签: java design-patterns decorator facade