业务代表模式(Business Delegate Pattern)用于对表示层和业务层解耦。它基本上是用来减少通信或对表示层代码中的业务层代码的远程查询功能。在业务层中我们有以下实体。
- 客户端(Client) - 表示层代码可以是 JSP、servlet 或 UI java 代码。
- 业务代表(Business Delegate) - 一个为客户端实体提供的入口类,它提供了对业务服务方法的访问。
- 查询服务(LookUp Service) - 查找服务对象负责获取相关的业务实现,并提供业务对象对业务代表对象的访问。
- 业务服务(Business Service) - 业务服务接口。实现了该业务服务的实体类,提供了实际的业务实现逻辑。
代码实现
//业务代表模式 public class BusinessRepresentativeMode { public static void main(String[] args) { BusinessDelegate businessDelegate = new BusinessDelegate(); businessDelegate.setBusinessServiceType("JMS"); Client client = new Client(businessDelegate); client.doTask(); businessDelegate.setBusinessServiceType("EJB"); client.doTask(); } } interface BusinessService { void doProcessing(); } //创建实体服务类。 class EJBService implements BusinessService { @Override public void doProcessing() { System.out.println("Processing task by invoking EJB Service"); } } class JMSService implements BusinessService { @Override public void doProcessing() { System.out.println("Processing task by invoking JMS Service"); } } //创建业务查询服务。 class BusinessLookUp { public BusinessService getBusinessService(String businessServiceType) { if (businessServiceType.equalsIgnoreCase("EJB")) { return new EJBService(); } return new JMSService(); } } //创建业务代表。 class BusinessDelegate { private BusinessLookUp businessLookUp = new BusinessLookUp(); private BusinessService businessService; private String businessServiceType; public void setBusinessServiceType(String businessServiceType) { this.businessServiceType = businessServiceType; } public void doTask() { businessService = businessLookUp.getBusinessService(businessServiceType); businessService.doProcessing(); } } class Client { private BusinessDelegate businessDelegate; public Client(BusinessDelegate businessDelegate) { this.businessDelegate = businessDelegate; } public void doTask() { businessDelegate.doTask(); } }