外观模式(门面模式)

一、概念介绍

  外观模式(Facade),他隐藏了系统的复杂性,并向客户端提供了一个可以访问系统的接口。这种类型的设计模式属于结构性模式。为子系统中的一组接口提供了一个统一的访问接口,这个接口使得子系统更容易被访问或者使用。 

二、角色及使用场景

  简单来说,该模式就是把一些复杂的流程封装成一个接口供给外部用户更简单的使用。这个模式中,设计到3个角色。

  1).门面角色:外观模式的核心。它被客户角色调用,它熟悉子系统的功能。内部根据客户角色的需求预定了几种功能的组合。

  2).子系统角色:实现了子系统的功能。它对客户角色和Facade时未知的。它内部可以有系统内的相互交互,也可以由供外界调用的接口。

  3).客户角色:通过调用Facede来完成要实现的功能。

  使用场景:

  1- 为复杂的模块或子系统提供外界访问的模块;

  2- 子系统相互独立;

       3- 在层析结构中,可以使用外观模式定义系统的每一层的入口。

三、实例

  下面,我们就通过一个简单的例子来实现该模式。

  每个Computer都有CPU、Memory、Disk。在Computer开启和关闭的时候,相应的部件也会开启和关闭,所以,使用了该外观模式后,会使用户和部件之间解耦。如:

具体实例

代码清单

首先是子系统类:

public class CPU {

    public void start(){
        System.out.println("cpu is start...");
    }

    public void shutdown(){
        System.out.println("cpu is shutdown...");
    }
}

--
public class Disk {

    public void start(){
        System.out.println("disk is start...");
    }

    public void shutdown(){
        System.out.println("disk is shutdown...");
    }
}
--
public class Memory {

    public void start(){
        System.out.println("Memory is start...");
    }

    public void shutdown(){
        System.out.println("Memory is shutdown...");
    }
}

然后是,门面类Facade

public class Computer {
    private CPU cpu;
    private Memory memory;
    private Disk disk;
    public Computer(){
         cpu = new CPU();
         memory = new Memory();
         disk = new Disk();
    }
    public void start(){
        System.out.println("Computer start begin");
        cpu.start();
        disk.start();
        memory.start();
        System.out.println("Computer start end");
    }

    public void shutdown(){
        System.out.println("Computer shutdown begin");
        cpu.shutdown();
        disk.shutdown();
        memory.shutdown();
        System.out.println("Computer shutdown end");
    }
}

最后为,客户角色。

public class Client {
    public static void main(String[] args) {
        Computer computer = new Computer();
        computer.start();
        System.out.println("==============");
        computer.shutdown();
    }
}

运行结果

Computer start begin
cpu is start...
disk is start...
Memory is start...
Computer start end
==============
Computer shutdown begin
cpu is shutdown...
disk is shutdown...
Memory is shutdown...
Computer shutdown end

从上面的实例来看,有了这个Facade类,也就是Computer类,用户就不用亲自去调用子系统中的Disk,Memory、CPU类了,不需要知道系统内部的实现细节,甚至都不用知道系统内部的构成。客户端只需要跟Facade交互就可以了。

四、优点

  - 松散耦合

  使得客户端和子系统之间解耦,让子系统内部的模块功能更容易扩展和维护;

  - 简单易用

  客户端根本不需要知道子系统内部的实现,或者根本不需要知道子系统内部的构成,它只需要跟Facade类交互即可。

  - 更好的划分访问层次

  有些方法是对系统外的,有些方法是系统内部相互交互的使用的。子系统把那些暴露给外部的功能集中到门面中,这样就可以实现客户端的使用,很好的隐藏了子系统内部的细节。

原文网址

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值