業(yè)務(wù)代表模式(Business Delegate Pattern)用于對(duì)表示層和業(yè)務(wù)層解耦。它基本上是用來(lái)減少通信或?qū)Ρ硎緦哟a中的業(yè)務(wù)層代碼的遠(yuǎn)程查詢功能。在業(yè)務(wù)層中我們有以下實(shí)體。
我們將創(chuàng)建 Client、BusinessDelegate、BusinessService、LookUpService、JMSService 和 EJBService 來(lái)表示業(yè)務(wù)代表模式中的各種實(shí)體。
BusinessDelegatePatternDemo,我們的演示類使用 BusinessDelegate 和 Client 來(lái)演示業(yè)務(wù)代表模式的用法。
創(chuàng)建 BusinessService 接口。
BusinessService.java
public interface BusinessService {
public void doProcessing();
}
創(chuàng)建實(shí)體服務(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 類來(lái)演示業(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();
}
}
驗(yàn)證輸出。
Processing task by invoking EJB Service
Processing task by invoking JMS Service
更多建議: