📜  业务委托模式

📅  最后修改于: 2021-09-10 02:49:06             🧑  作者: Mango

业务委托充当客户端业务抽象,它为业务服务的实现提供抽象,从而隐藏业务服务的实现。它减少了表示层客户端和系统业务服务之间的耦合。

UML 图业务委托模式

设计组件

  • 业务委托:客户端实体的单个入口点类,用于提供对业务服务方法的访问。
  • LookUp Service: Lookup 服务对象负责获取相关的业务实现,并提供业务对象对业务委托对象的访问。
  • 业务服务:业务服务接口。具体类实现此业务服务以提供实际的业务实现逻辑。

让我们看一个业务委托模式的例子。

interface BusinessService
{
    public void doProcessing();
}
  
class OneService implements BusinessService
{
    public void doProcessing() 
    {
        System.out.println("Processed Service One");
    }
}
  
class TwoService implements BusinessService 
{
    public void doProcessing() 
    {
        System.out.println("Processed Service Two");
    }
}
  
class BusinessLookUp 
{
    public BusinessService getBusinessService(String serviceType)
    {
        if(serviceType.equalsIgnoreCase("One"))
        {
            return new OneService();
        }
        else
        {
            return new TwoService();
        }
   }
}
  
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();        
    }
}
  
class Client 
{
    BusinessDelegate businessService;
  
    public Client(BusinessDelegate businessService)
    {
        this.businessService  = businessService;
    }
  
    public void doTask()
    {        
        businessService.doTask();
    }
}
  
class BusinessDelegatePattern
{
    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();
    }
}

输出:

Processed Service One
Processed Service Two

好处 :

  • 业务委托减少了表示层客户端和业务服务之间的耦合。
  • 业务委托隐藏了业务服务的底层实现细节。

缺点:

  • 由于增加了应用程序中类数量的额外层而导致的维护。