设计模式--外观模式(门面模式)

简介

基本内容
外观模式(Facade),也叫 “ 过程模式:外观模式为子系统中的一组接口提供一个一致的界面,此模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。
外观模式通过定义一个一致的接口,用以屏蔽内部子系统的细节,使得调用端只需跟这个接口发生调用,而无需关心这个子系统的内部细节。

外观模式(Facade),他隐藏了系统的复杂性,并向客户端提供了一个可以访问系统的接口。这种类型的设计模式属于结构性模式。为子系统中的一组接口提供了一个统一的访问接口,这个接口使得子系统更容易被访问或者使用。
外观模式类图如下:
在这里插入图片描述
外观模式主要包含角色:
外观类(Facade): 也叫门面角色,是外观模式的核心。为调用端提供统一的调用接口, 外观类知道哪些子系统负责处理请求,从而将调用端的请求代理给适当子系统对象。
调用者(Client): 外观接口的调用者。
子系统的集合:指模块或者子系统,处理 Facade对象指派的任务,他是功能的实际提供者。

示例

1.创建一个接口
依旧以图形类为例

public interface Shape {
    void draw();
}

2.创建接口实现类

public class Rectangle implements Shape {
    @Override
    public void draw() {
        System.out.println("Rectangle::draw()");
    }
}
public class Square implements Shape {
    @Override
    public void draw() {
        System.out.println("Square::draw()");
    }
}

public class Circle implements Shape {
    @Override
    public void draw() {
        System.out.println("Circle::draw()");
    }
}

3.创建外观类(门面角色)

public class FacadeShape {
    private Shape circle;
    private Shape rectangle;
    private Shape square;
    public FacadeShape() {
        circle = new Circle();
        rectangle = new Rectangle();
        square = new Square();
    }

    public void drawCircle(){
        circle.draw();
    }
    public void drawRectangle(){
        rectangle.draw();
    }
    public void drawSquare(){
        square.draw();
    }
}

4.main方法验证

public class FacadeMain {
    public static void main(String[] args) {
        FacadeShape facadeShape = new FacadeShape();
        facadeShape.drawCircle();
        facadeShape.drawRectangle();
        facadeShape.drawSquare();
    }
}

在这里插入图片描述

分析

使用场景:
1、为复杂的模块或子系统提供外界访问的模块。
2、子系统相对独立。
3、预防低水平人员带来的风险。
优缺点:
优点: 1、减少系统相互依赖。 2、提高灵活性。 3、提高了安全性。
缺点:不符合开闭原则,如果要改东西很麻烦,继承重写都不合适。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值