实例
我们将创建一个Client,BusinessDelegate,BusnessService,LookUpService,JMSService和EJBService,它们代表业务代表模式的各种实体。
我们的演示类BusinessDelegatePatternDemo,将使用BusinessDelegate和Client演示使用业务委托模式的。
第1步 - 创建BusinessService接口。 BusinessService.java
public interface BusinessService {
public void doProcessing();
}
第2步 - 创建具体的服务类。 EJBService.java,JMSService.java
public class EJBService implements BusinessService {
@Override
public void doProcessing() {
System.out.println("Processing task by invoking EJB Service");
}
}
public class JMSService implements BusinessService {
@Override
public void doProcessing() {
System.out.println("Processing task by invoking JMS Service");
}
}
第3步 - 创建业务查找服务。 BusinessLookUp.java
public class BusinessLookUp {
public BusinessService getBusinessService(String serviceType){
if(serviceType.equalsIgnoreCase("EJB")){
return new EJBService();
}
else {
return new JMSService();
}
}
}
步骤4 - 创建业务代表。 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();
}
}
第5步 创建客户端。Client.java
public class Client {
BusinessDelegate businessService;
public Client(BusinessDelegate businessService){
this.businessService = businessService;
}
public void doTask(){
businessService.doTask();
}
}
第6步 使用BusinessDelegate和Client类来演示Business Delegate模式。 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();
}
}
步骤7 - 验证输出。
Processing task by invoking EJB Service
Processing task by invoking JMS Service