GoF23种设计模式之结构型模式之外观模式

一、概述
        为子系统中的一组接口提供一个一致的界面,外观模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。
二、适用性
1.当你要为一个复杂子系统提供一个简单接口的时候。子系统往往因为不断演化而变得越来越复杂。大多数模式使用时都会产生更多更小的类。这使得子系统更具可重用性,也更容易对子系统进行定制,但这也给那些不需要定制子系统的用户带来一些使用上的困难。外观模式可以提供一个简单的缺省视图,这一视图对大多数用户来说已经足够,而那些需要更多的可定制性的用户可以越过外观层。
2.客户程序与抽象类的实现部分之间存在着很大的依赖性的时候。引入外观模式将这个子系统与客户以及其他的子系统分离,可以提高子系统的独立性和可移植性。
3.当你需要构建一个层次结构的子系统的时候,使用外观模式定义子系统中每层的入口点。如果子系统之间是相互依赖的,你可以让它们仅通过外观层进行通讯,从而简化了它们之间的依赖关系。
三、参与者
1.Facade:知道哪些子系统类负责处理请求。将客户的请求代理给适当的子系统对象。
2.Subsystemclasses:实现子系统的功能。处理由Facade对象指派的任务。没有Facade对象的任何相关信息;即没有指向Facade对象的指针。
四、类图

五、示例
Facade
package cn.lynn.facade;

public class ServiceManager {

    private IAuthService authService;
    private ILogService logService;
    private IFileService fileService;

    public ServiceManager() {
        authService = new AuthServiceImpl();
        logService = new LogServiceImpl();
        fileService = new FileServiceImpl();
    }

    public void service() {
        authService.auth();
        logService.log();
        fileService.file();
    }
}
Subsystemclasses
package cn.lynn.facade;

public class AuthServiceImpl implements IAuthService {

    @Override
    public void auth() {
        System.out.println("实现认证服务!");
    }

}
package cn.lynn.facade;

public class LogServiceImpl implements ILogService {

    @Override
    public void log() {
        System.out.println("实现日志服务!");
    }

}
package cn.lynn.facade;

public class FileServiceImpl implements IFileService {

    @Override
    public void file() {
        System.out.println("实现文件服务!");
    }

}
Client
package cn.lynn.facade;

public class Client {

    public static void main(String[] args) {
        ServiceManager serviceManager = new ServiceManager();
        serviceManager.service();
    }

}
Result
实现认证服务!
实现日志服务!
实现文件服务!
原文地址:https://www.cnblogs.com/innosight/p/3271148.html