Radio

一个小小程序员

0%

业务代表模式

业务代表模式

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

客户端(Client) - 表示层代码可以是 JSP、servlet 或 UI java 代码。

业务代表(Business Delegate) - 一个为客户端实体提供的入口类,它提供了对业务服务方法的访问。

查询服务(LookUp Service) - 查找服务对象负责获取相关的业务实现,并提供业务对象对业务代表对象的访问。

业务服务(Business Service) - 业务服务接口。实现了该业务服务的实体类,提供了实际的业务实现逻辑。

示例演示:
  1. 创建peopleService接口

    1
    2
    3
    4
    5
    package test.business;

    public interface PeopleService {
    void doSomething();
    }
  2. 创建两个服务实体类

    1
    2
    3
    4
    5
    6
    7
    8
    package test.business;

    public class EatService implements PeopleService{
    @Override
    public void doSomething() {
    System.out.println("eat...");
    }
    }
    1
    2
    3
    4
    5
    6
    7
    8
    package test.business;

    public class SleepService implements PeopleService{
    @Override
    public void doSomething() {
    System.out.println("sleep...");
    }
    }
  3. 创建查询服务

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    package test.business;

    public class BusinessSeach {

    public PeopleService seach(String serviceType) {
    if (serviceType.equalsIgnoreCase("eat")) {
    return new EatService();
    } else {
    return new SleepService();
    }
    }

    }
  4. 创建业务代表

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    package test.business;

    public class BusinessDelegate {
    private BusinessSeach businessSeach = new BusinessSeach();
    private PeopleService peopleService;
    private String servcieType;

    public void setServiceType(String servcieType) {
    this.servcieType = servcieType;
    }

    public void doTask() {
    peopleService = businessSeach.seach(servcieType);
    peopleService.doSomething();
    }

    }
  5. 完成上述步骤,我们就可以开始演示了

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    package test.business;

    public class BusinessDelegateDemo {

    public static void main(String[] args) {
    BusinessDelegate businessDelegate = new BusinessDelegate();
    Client client = new Client(businessDelegate);

    businessDelegate.setServiceType("eat");
    client.doTask();

    businessDelegate.setServiceType("sleep");
    client.doTask();
    }
    }

    运行结果:

    1
    2
    eat...
    sleep...

欢迎关注我的其它发布渠道