软件设计模式之外观模式

软件设计模式之外观模式

外观模式隐藏了系统的复杂性,并提供了到客户端的接口,客户端可以使用该接口访问系统。

技术开发 编程 技术框架 技术发展

 

软件设计模式之外观模式

外观模式隐藏了系统的复杂性,并提供了到客户端的接口,客户端可以使用该接口访问系统。

外观模式隐藏了系统的复杂性,并提供了到客户端的接口,客户端可以使用该接口访问系统。这种设计模式属于结构模式,因为该模式向现有系统添加了接口以隐藏其复杂性。此模式涉及一个类,该类提供了客户端所需的简化方法,并将调用委托给现有系统类的方法。

实作

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

ShapeMaker类使用具体的类将用户调用委派给这些类。FacadePatternDemo,我们的演示课,将使用ShapeMaker类来显示结果。


facade_pattern_uml_diagram.jpg

第1步

创建一个接口。

Shape.java


public interface Shape {

   void draw();

}

第2步

创建实现相同接口的具体类。

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

   }

}

第3步

创建一个外观类。


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

   }

}

第4步

使用立面绘制各种类型的形状。


FacadePatternDemo.java


public class FacadePatternDemo {

   public static void main(String[] args) {

      ShapeMaker shapeMaker = new ShapeMaker();


      shapeMaker.drawCircle();

      shapeMaker.drawRectangle();

      shapeMaker.drawSquare();

   }

}

第5步

验证输出。


Circle::draw()

Rectangle::draw()

Square::draw()

技术开发 编程 技术框架 技术发展