Java

设计模式之业务代表模式

2019-07-19  本文已影响0人  盗梦者_56f2

简介

业务代表模式(Business Delegate Pattern)用于对表示层和业务层解耦。它基本上是用来减少通信或对表示层代码中的业务层代码的远程查询功能。在业务层中我们有以下实体。

实现

创建 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
上一篇下一篇

猜你喜欢

热点阅读