业务代表模式

2019-04-23  本文已影响0人  蜗牛ICU

前言:

因为现在设计模式在网络上已经泛滥,但是还是有好多程序员不能够灵活的运用设计模式,这个是对设计模式简单的介绍,因为网络上比较多类似的文章,所以本人就从网络上抄了一部分,等23种设计模式整理完成之后会根据实际的需求利用设计模式在代码中设计一些开源的插件,请继续关注。
原版[菜鸟教程]

简介:

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

案例:

第一步: 创建接口:

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();
   }
}

第六步: 使用 BusinessDelegate 和 Client 类来演示业务代表模式:

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

上一篇下一篇

猜你喜欢

热点阅读