業務代理模式用於解耦表示層和業務層。 它基本上用於減少表示層程式碼中的業務層程式碼的通訊或遠端查詢功能。在業務層有以下實體。
在這個實現範例中,將建立一個業務代理模式的各種實體的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