業(yè)務(wù)代理模式用于解耦表示層和業(yè)務(wù)層。 它基本上用于減少表示層代碼中的業(yè)務(wù)層代碼的通信或遠程查找功能。在業(yè)務(wù)層有以下實體。
在這個實現(xiàn)實例中,將創(chuàng)建一個業(yè)務(wù)代理模式的各種實體的Client
,BusinessDelegate
,BusinessService
,LookUpService
,JMSService
和EJBService
。
BusinessDelegatePatternDemo
這是一個演示類,將使用 BusinessDelegate
和 Client
來演示業(yè)務(wù)代理模式的使用。
業(yè)務(wù)代理模式示例的結(jié)構(gòu)如下圖所示 -
創(chuàng)建BusinessService
接口,其代碼如下所示 -
BusinessService.java
public interface BusinessService {
public void doProcessing();
}
創(chuàng)建具體的服務(wù)類,其代碼如下所示 -
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");
}
}
創(chuàng)建業(yè)務(wù)查找服務(wù),其代碼如下所示 -
BusinessLookUp.java
public class BusinessLookUp {
public BusinessService getBusinessService(String serviceType){
if(serviceType.equalsIgnoreCase("EJB")){
return new EJBService();
}
else {
return new JMSService();
}
}
}
創(chuàng)建業(yè)務(wù)代理,其代碼如下所示 -
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();
}
}
創(chuàng)建客戶端,其代碼如下所示 -
Client.java
public class Client {
BusinessDelegate businessService;
public Client(BusinessDelegate businessService){
this.businessService = businessService;
}
public void doTask(){
businessService.doTask();
}
}
使用BusinessDelegate
和Client
類來演示業(yè)務(wù)代理模式,其代碼如下所示 -
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();
}
}
驗證輸出,執(zhí)行上面的代碼得到以下結(jié)果 -
Processing task by invoking EJB Service
Processing task by invoking JMS Service