• 设计模式之外观模式


    外观模式给子系统的一组接口提供了一致的访问界面,提供了一个高层访问接口,降低了访问复杂系统内部子系统的复杂度。在客户端和负责系统间增加一层,将调用顺序、依赖关系等处理好,比如说Java的三层开发模式。

    外观模式的优点是减少系统相互依赖,提高灵活性、安全性;缺点是不符合开闭原则,如果要改东西很麻,继承重写都不合适。

    1. 创建形状接口及其实现;
    public interface Shape {
        void draw();
    }
    
    public class Rectangle implements Shape {
        @Override
        public void draw() {
            System.out.println("Inside Rectangle::draw method.");
        }
    }
    
    public class Circle implements Shape {
    
        @Override
        public void draw(){
            System.out.println("Inside Circle::draw method.");
        }
    
    }
    
    public class Square implements Shape {
    
        @Override
        public void draw(){
            System.out.println("Inside Square::draw method.");
        }
    
    }
    
    public class UnknownShape implements Shape {
    
        @Override
        public void draw(){
            System.out.println("Inside UnknownShape::draw method.");
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    1. 创建外观类,构造函数中提供了对图形接口的实现类的引用;
    public class ShapeMaker {
    
        private Shape circle;
        private Shape rectangle;
        private Shape unknownShape;
        private Shape square;
    
        ShapeMaker(){
            circle = new Circle();
            rectangle = new Rectangle();
            square = new Square();
            unknownShape = new UnknownShape();
        }
    
        void drawCircle(){
            circle.draw();
        }
    
        void drawRectangle(){
            rectangle.draw();
        }
    
        void drawSquare(){
            square.draw();
        }
    
        void drawUnknownShape(){
            unknownShape.draw();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    1. 使用外观类画出各种图形。
    public class FacadeInstance {
    
        public static void main(String[] args) {
            ShapeMaker maker = new ShapeMaker();
            maker.drawCircle();
            maker.drawRectangle();
            maker.drawSquare();
            maker.drawUnknownShape();
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
  • 相关阅读:
    C++: 继承
    【Linux】基础IO
    微信小程序登录获取不到头像和昵称解决办法!
    kingbase表或者索引坏块问题解决办法
    20240424 diary
    JSTL标签库
    Python---数据序列中的公共方法
    使用c:forEach出现页面空白,没有数据
    vue3中的reactive和ref
    你还有什么问题吗?
  • 原文地址:https://blog.csdn.net/dolly_baby/article/details/126518471