业务代理模式用于解耦表示层和业务层。 它基本上用于减少表示层代码中的业务层代码的通信或远程查找功能。在业务层有以下实体。
在这个实现实例中,将创建一个业务代理模式的各种实体的Client
,BusinessDelegate
,BusinessService
,LookUpService
,JMSService
和EJBService
。
BusinessDelegatePatternDemo
这是一个演示类,将使用 BusinessDelegate
和 Client
来演示业务代理模式的使用。
业务代理模式示例的结构如下图所示 -
创建BusinessService
接口,其代码如下所示 -
BusinessService.java
public interface BusinessService { public void doProcessing(); }
创建具体的服务类,其代码如下所示 -
EJBService.java
public class EJBService implements BusinessService { @Override public void doProcessing() { System.out.println("Processing task by invoking EJB Service"); } }
JMSService.java
public class JMSService implements BusinessService { @Override public void doProcessing() { System.out.println("Processing task by invoking JMS Service"); } }
创建业务查找服务,其代码如下所示 -
BusinessLookUp.java
public class BusinessLookUp { public BusinessService getBusinessService(String serviceType){ if(serviceType.equalsIgnoreCase("EJB")){ return new EJBService(); } else { return new JMSService(); } } }
创建业务代理,其代码如下所示 -
BusinessDelegate.java
public class BusinessDelegate { private BusinessLookUp lookupService = new BusinessLookUp(); private BusinessService businessService; private String serviceType; public void setServiceType(String serviceType){ this.serviceType = serviceType; } public void doTask(){ businessService = lookupService.getBusinessService(serviceType); businessService.doProcessing(); } }
创建客户端,其代码如下所示 -
Client.java
public class Client { BusinessDelegate businessService; public Client(BusinessDelegate businessService){ this.businessService = businessService; } public void doTask(){ businessService.doTask(); } }
使用BusinessDelegate
和Client
类来演示业务代理模式,其代码如下所示 -
BusinessDelegatePatternDemo.java
public class BusinessDelegatePatternDemo { public static void main(String[] args) { BusinessDelegate businessDelegate = new BusinessDelegate(); businessDelegate.setServiceType("EJB"); Client client = new Client(businessDelegate); client.doTask(); businessDelegate.setServiceType("JMS"); client.doTask(); } }
验证输出,执行上面的代码得到以下结果 -
Processing task by invoking EJB Service Processing task by invoking JMS Service