设计模式之外观模式——Java语言描述

外观模式隐藏系统的复杂性,并向客户端提供了一个客户端可以访问系统的接口。它想现有的系统添加了一个接口,以隐藏系统的复杂性

介绍

意图

为子系统中的一组接口提供了一个一致的界面,外观模式定义了一个高层接口,这个接口使得这一子系统更加容易使用

应用实例

  1. 电脑只要按下开机键,就会自动执行开机的程序
  2. Java的三层开发模式

优点

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

缺点

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

实现

我们将创建一个 Shape 接口和实现了 Shape 接口的实体类。下一步是定义一个外观类 ShapeMaker。

ShapeMaker 类使用实体类来代表用户对这些类的调用。FacadePatternDemo,我们的演示类使用 ShapeMaker 类来显示结果。

创建Shape接口

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()

猜你喜欢

转载自www.cnblogs.com/AmosH/p/10259656.html