• 设计模式之外观模式——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()
    
  • 相关阅读:
    mac的webdriver自动化
    MongoDB win安装后无法远程连接访问
    Fiddler的一些坑: !SecureClientPipeDirect failed: System.IO.IOException
    Mac终端用Sublime打开指定文件或文件夹
    [Spring常见问题]java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener
    Flask_Flask-Mail邮件扩展(十三)
    Flask_Flask-Migrate数据迁移扩展(十二)
    Flask + flask_sqlalchemy + jq 完成书籍展示、新增、删除功能
    Flask_CSRF保护(十一)
    SQLAlchemy(十)
  • 原文地址:https://www.cnblogs.com/AmosH/p/10259656.html
Copyright © 2020-2023  润新知