Design Pattern 简明教程
Design Patterns - Business Delegate Pattern
业务委托模式用于将表示层和业务层解耦。它基本上用于减少表示层代码对业务层代码的通信或远程查找功能。在业务层中,我们有以下实体:
-
Client - 表示层代码可能是 JSP、servlet 或 UI Java 代码。
-
Business Delegate - 客户端实体的一个单一入口点类,用于提供对业务服务方法的访问。
-
LookUp Service - 查找服务对象负责获取相关的业务实现,并向业务委托对象提供对业务对象的访问。
-
Business Service - 业务服务接口。具体类实现这个业务服务来提供实际的业务实现逻辑。
Implementation
我们将创建 Client、BusinessDelegate、BusinessService、LookUpService、JMSService 和 EJBService 来表示业务委托模式的不同实体。
BusinessDelegatePatternDemo(我们的演示类)将使用 BusinessDelegate 和 Client 来演示业务委托模式。
Step 1
创建 BusinessService 界面。
BusinessService.java
public interface BusinessService {
public void doProcessing();
}
Step 2
创建具体的 Service 类。
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");
}
}
Step 3
创建业务查找服务。
BusinessLookUp.java
public class BusinessLookUp {
public BusinessService getBusinessService(String serviceType){
if(serviceType.equalsIgnoreCase("EJB")){
return new EJBService();
}
else {
return new JMSService();
}
}
}
Step 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();
}
}
Step 5
创建客户端。
Client.java
public class Client {
BusinessDelegate businessService;
public Client(BusinessDelegate businessService){
this.businessService = businessService;
}
public void doTask(){
businessService.doTask();
}
}
Step 6
使用 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();
}
}