业务代表模式(Business Delegate Pattern)用于对表示层和业务层解耦。它基本上是用来减少通信或者表示层代码中的业务层代码的远程查询功能。在业务层中能中我们有一下实体。
- 客户端(Client)-表示层代码可以是jsp、servlet或UI java代码。
- 业务代表(Business Delegate)-一个为客户端实体提供的人口类,它提供了对业务服务方法的访问。
- 查询服务(LookUp Service)-查找服务对象负责获取相关的业务实现,并提供了业务对象对业务代表对象的访问。
- 业务服务(Business Service)-业务服务接口。实现了该业务服务的实体类,提供了实际的业务实现逻辑。
实现:
创建Client、BusinessDelegate、BusinessService、LookUpService、JMSService和EJBService来表示业务代表模式中的各种实体。
创建BusinessService接口:
public interface BusinessService {
public void doProcessing();
}
创建实体服务类:
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");
}
}
创建业务查询服务:
//创建业务查询服务
public class BusinessLookUp {
public BusinessService getBusinessService(String serviceType){
if (serviceType.equalsIgnoreCase("EJB")){
return new EJBService();
}else{
return new JMSService();
}
}
}
创建业务代表:
//创建业务代表
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();
}
}
创建客户端:
//创建客户端
public class Client {
BusinessDelegate businessService;
public Client(BusinessDelegate businessService){
this.businessService = businessService;
}
public void doTask(){
businessService.doTask();
}
}
演示业务代表模式:
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