《设计模式》 - 8. 外观模式( Facade )

    xiaoxiao2021-03-25  97

    《设计模式》 - 8. 外观模式( Facade ) :

    语言 : C#

    说明 :

    第一步 : 通过 Shape 接口 , 衍生出两个派生类 正方形 (Square) 和 圆形 (Circle) , Square 和 Circle 两个类里都具有 绘制 (draw) 函数 . 第二步 : 然后实例化 Maker 类 , 通过 maker 来调用 draw 函数绘制图形 , 不用管里面的具体实现细节 , 在较大的项目中 , 可以告诉新人接口作用 , 直接调用 , 而不必花时间讲解实现逻辑 .

    作用 :

    减少系统间的相互依赖 .增加灵活性 .避免低水平程序员带来的风险 .

    弊端 :

    继承和重写都不合适 , 修改很麻烦 .不符合开闭原则 .

    图示 :

    实现 :

    对图示中的内容稍微简化了一些 , 大致思路是一样的 .

    实现接口Shape , 重写 draw方法 . namespace DesignPattern { //接口 Shape public interface Shape { void draw(); } //正方形 Square public class Square : Shape { public void draw() { Console.WriteLine("画正方形"); } } //圆形 Circle public class Circle : Shape { public void draw() { Console.WriteLine("画圆形"); } } 创建一个 Maker 外观类 , 对外提供接口 , 对内隐藏实现细节 . //外观类 public class Maker { private Shape square; private Shape circle; public Maker() { square = new Square(); circle = new Circle(); } //画正方形 public void drawSquare() { square.draw(); } //画圆形 public void drawCircle() { circle.draw(); } } 实例化外观类 ( Maker ) , 调用 Maker里的接口 . //外观模式 public class FacadePattern { static void Main() { //实例化 外观类 Maker maker = new Maker(); //调用绘制方法 maker.drawCircle(); maker.drawSquare(); } } }

    结果 :

    转载请注明原文地址: https://ju.6miu.com/read-23211.html

    最新回复(0)