Java设计模式——外观模式(Facade Pattern)

来源:互联网 发布:聚拓数据录入邀请码 编辑:程序博客网 时间:2024/05/16 14:34

外观模式的定义

外观模式(Facade Pattern)隐藏系统的复杂性,并向客户端提供了一个客户端可以访问系统的接口。这种类型的设计模式属于结构型模式,它向现有的系统添加一个接口,来隐藏系统的复杂性。
这种模式涉及到一个单一的类,该类提供了客户端请求的简化方法和对现有系统类方法的委托调用。

外观模式的代码示例

创建一个 Shape 接口和实现了 Shape 接口的实体类。下一步是定义一个外观类 ShapeMaker。
ShapeMaker 类使用实体类来代表用户对这些类的调用。FacadePatternDemo,我们的演示类使用 ShapeMaker 类来显示结果。

UML图

这里写图片描述

第一步:创建一个接口

Shape.java

public interface Shape {   void draw();}

第二步:创建实现接口的实体类

Rectangle.java

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

Square.java

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

Circle.java

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

第三步:创建一个外观类

ShapeMaker.java

public class ShapeMaker {   private Shape circle;   private Shape rectangle;   private Shape square;   public ShapeMaker() {      circle = new Circle();      rectangle = new Rectangle();      square = new Square();   }   public void drawCircle(){      circle.draw();   }   public void drawRectangle(){      rectangle.draw();   }   public void drawSquare(){      square.draw();   }}

第四步:使用该外观类画出各种类型的形状

FacadePatternDemo.java

public class FacadePatternDemo {   public static void main(String[] args) {      ShapeMaker shapeMaker = new ShapeMaker();      shapeMaker.drawCircle();      shapeMaker.drawRectangle();      shapeMaker.drawSquare();           }}

第五步:验证输出

Circle::draw()Rectangle::draw()Square::draw()

外观模式的优缺点

优点

1、减少系统相互依赖。
2、提高灵活性。
3、提高了安全性。

缺点

不符合开闭原则,如果要改东西很麻烦,继承重写都不合适。

适用场景

1、为复杂的模块或子系统提供外界访问的模块。
2、子系统相对独立。
3、预防低水平人员带来的风险。

阅读全文
0 0
原创粉丝点击