设计模式——外观模式

                           设计模式——外观模式

 

  

外观模式(Facade Pattern)隐藏系统的复杂性,并向客户端提供了一个客户端可以访问系统的接口。这种类型的设计模式属于结构型模式,它向现有的系统添加一个接口,来隐藏系统的复杂性。

这种模式涉及到一个单一的类,该类提供了客户端请求的简化方法和对现有系统类方法的委托调用。

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

主要解决:降低访问复杂系统的内部子系统时的复杂度,简化客户端与之的接口。

 

   实现:

      UML类图

 

 

     具体实现代码:

 

 1 定义接口: Shape
 2 public interface Shape {
 3     void draw();
 4 }
 5 
 6  定义了三个类都分别实现了接口中的方法。
 7 public class Rectangle implements Shape{
 8 
 9     @Override
10     public void draw() {
11         // TODO 自动生成的方法存根
12         System.out.println("Rectangle::draw()");
13     }
14  
15 }
16 
17 public class Circle implements  Shape{
18 
19     @Override
20     public void draw() {
21         // TODO 自动生成的方法存根
22         System.out.println("Circle::draw()");
23     }
24   
25     
26 }
27 
28 public class Square implements Shape {
29 
30     @Override
31     public void draw() {
32         // TODO 自动生成的方法存根
33         System.out.println("Square::draw()");
34     }
35   
36 }
37 
38 定义了一个ShapeMarke类,实现上面三个类的方法,以接口Shape为类型来定义变量
39 
40 public class ShapeMarke {
41   
42     private Shape circle;
43     private Shape rectangle;
44     private Shape square;
45   
46      public ShapeMarke()
47      {
48          circle = new Circle();
49          rectangle = new Rectangle();
50          square = new Square(); 
51      }
52      
53      public void drawCircle()
54      {
55          circle.draw();
56      }
57      
58      public void drawRectangle()
59      {
60          rectangle.draw();
61      }
62      
63      public void drawSquare()
64      {
65          square.draw();
66      }
67 
68 
69 }
70     
71 公共测试类
72 public class FacadePatternDemo {
73     public static void main(String[] args)
74     {
75         ShapeMarke ShapeMarke = new ShapeMarke();
76           ShapeMarke.drawCircle();
77           ShapeMarke.drawRectangle();
78           ShapeMarke.drawSquare();
79     }
80 
81 }
82     
83     
84       
85     

 

 

   运行结果如图:

  

 

 

 

 

 

 

 

posted @ 2016-05-18 11:26  PengWenHao  阅读(172)  评论(0编辑  收藏  举报