Business Delegate Design Pattern
Overview
The business delegate is used to separate the business side and presentation side. The business side is made up of 4 parts:
- Client — The presentation code to display the data
- Business Delegate — Provides access to the business service methods which the client uses
- LookUp Service — Responsible to get relative business implementation and provides business object access to business delegate object
- Business Service — The concrete class implements the business service interface to provide business implementation logic
Implementation
BusinessService.java
public interface BusinessService {
public void doSomething();
}
The business interface that the concrete class implements
ServiceOne.java
public class ServiceOne implements BusinessService {
@Override
public void doSomething() {
System.out.println("Something One!");
}
}
ServiceOne.java
public class ServiceTwo implements BusinessService {
@Override
public void doSomething() {
System.out.println("Something Two!");
}
}
The concrete business service that implements the business interface.
LookUp.java
public class LookUp {
public BusinessService getBusinessService(String serviceType){
if(serviceType.equalsIgnoreCase("one")){
return new ServiceOne();
}
else {
return new ServiceTwo();
}
}
}
LookUp service provides the concrete business service based on the string provided.
BusinessDelegate.java
public class BusinessDelegate {
private LookUp lookupService = new LookUp();
private BusinessService businessService;
private String serviceType;
public void setServiceType(String serviceType){
this.serviceType = serviceType;
}
public void doTask(){
businessService = lookupService.getBusinessService(serviceType);
businessService.doSomething();
}
}
The business delegate is what the client uses to access the business service. The client can change which service to use based on the service type.
Client.java
public class Client {
BusinessDelegate businessDelegate;
public Client(BusinessDelegate businessDelegate){
this.businessDelegate = businessDelegate;
}
public void doTask(){
businessService.doTask();
}
}
Demo.java
public class Demo {
public static void main(String[] args) {
BusinessDelegate businessDelegate = new BusinessDelegate();
businessDelegate.setServiceType("one");
Client client = new Client(businessDelegate);
client.doTask();
businessDelegate.setServiceType("two");
client.doTask();
}
}>> Something One!
>> Something Two!
Conclusion
The business delegate design pattern was more popular in the early days with Enterprise Java Beans(EJB). Now with the popularity of Spring and dependency inject this design pattern has lost a lot of significance. But when it is used it reduces coupling with the business and client side and it hides the implementation of the business service. However, it adds an extra layer so it increase the effort needed to maintain the code.