业务代表模式(Business Delegate Pattern)

业务代码模式其实也是一种分层模型,分为业务服务层,服务查询层,业务代表层,客户端层。

业务代表模式的实例

假设我们有以下业务服务层。

  1. class EJBService {
  2. doProcessing() {
  3. console.log("Processing task by invoking EJB Service");
  4. }
  5. }
  6. class JMSService {
  7. doProcessing() {
  8. console.log("Processing task by invoking JMS Service");
  9. }
  10. }

服务查询层能对服务进行查找。

  1. class BusinessLookUp {
  2. getBusinessService(serviceType){
  3. switch(serviceType.toUpperCase()) {
  4. case 'EJB':
  5. return new EJBService();
  6. default:
  7. return new JMSService();
  8. }
  9. }
  10. }

定义业务代表

  1. class BusinessDelegate {
  2. constructor() {
  3. this.lookupService = new BusinessLookUp();
  4. }
  5. setServiceType(serviceType){
  6. this.serviceType = serviceType;
  7. }
  8. doTask(){
  9. this.businessService = this.lookupService.getBusinessService(this.serviceType);
  10. this.businessService.doProcessing();
  11. }
  12. }

定义客户端

  1. class Client {
  2. constructor(businessService){
  3. this.businessService = businessService;
  4. }
  5. doTask(){
  6. this.businessService.doTask();
  7. }
  8. }

使用业务代表和客户端交互

  1. const businessDelegate = new BusinessDelegate();
  2. businessDelegate.setServiceType("EJB");
  3. const client = new Client(businessDelegate);
  4. client.doTask();
  5. businessDelegate.setServiceType("JMS");
  6. client.doTask();

业务代表模式的优势

统一了业务出口,客户端不需要关心底层的模型,只需要关系业务代表暴露的模型。