业务代表模式(business delegate pattern)用于对表示层和业务层解耦。它基本上是用来减少通信或对表示层代码中的业务层代码的远程查询功能。在业务层中我们有以下实体。
客户端(client) - 表示层代码可以是 jsp、servlet 或 ui java 代码。
业务代表(business delegate) - 一个为客户端实体提供的入口类,它提供了对业务服务方法的访问。
查询服务(lookup service) - 查找服务对象负责获取相关的业务实现,并提供业务对象对业务代表对象的访问。
业务服务(business service) - 业务服务接口。实现了该业务服务的实体类,提供了实际的业务实现逻辑。
实现
我们将创建 client、businessdelegate、businessservice、lookupservice、jmsservice 和 e**service 来表示业务代表模式中的各种实体。
businessdelegatepatterndemo 类使用 businessdelegate 和 client 来演示业务代表模式的用法。
步骤 1
创建 businessservice 接口。
businessservice.java
public interface businessservice {
public void doprocessing();
}
步骤 2
创建实体服务类。
e**service.java
public class e**service implements businessservice {
@override
public void doprocessing() {
system.out.println("processing task by invoking e** service");
}
}
jmsservice.java
public class jmsservice implements businessservice {
@override
public void doprocessing() {
system.out.println("processing task by invoking jms service");
}
}
步骤 3
创建业务查询服务。
businesslookup.java
public class businesslookup {
public businessservice getbusinessservice(string servicetype){
if(servicetype.equalsignorecase("e**")){
return new e**service();
}else {
return new jmsservice();
}
}
}
步骤 4
创建业务代表。
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();
}
}
步骤 5
创建客户端。
client.java
public class client {
businessdelegate businessservice;
public client(businessdelegate businessservice){
this.businessservice = businessservice;
}
public void dotask(){
businessservice.dotask();
}
}
步骤 6
使用 businessdelegate 和 client 类来演示业务代表模式。
businessdelegatepatterndemo.java
public class businessdelegatepatterndemo {
public static void main(string[] args) {
businessdelegate businessdelegate = new businessdelegate();
businessdelegate.setservicetype("e**");
client client = new client(businessdelegate);
client.dotask();
businessdelegate.setservicetype("jms");
client.dotask();
}
}
步骤 7
执行程序,输出结果:
processing task by invoking e** service
processing task by invoking jms service