外观模式

  • 外观模式

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

  • UML图

  

  • 案例:  股民投资股票 ——> 股民通过购买基金,职业经理人投资股票

 未使用设计模式:

    

 1 package facade;
 2 
 3 /**
 4  * 股票1 5  */
 6 public class Stock1 {
 7 
 8     //买股票
 9     public void buy() {
10         System.out.println("股票1买入");
11     }
12 
13     public void sell(){
14         System.out.println("股票1卖出");
15     }
16 }
17 package facade;
18 
19 /**
20  * 股票2
21  */
22 public class Stock2 {
23 
24     //买股票
25     public void buy() {
26         System.out.println("股票2买入");
27     }
28 
29     public void sell(){
30         System.out.println("股票2卖出");
31     }
32 }
33 package facade;
34 
35 /**
36  * 股票3
37  */
38 public class Stock3 {
39 
40     //买股票
41     public void buy() {
42         System.out.println("股票3买入");
43     }
44 
45     public void sell(){
46         System.out.println("股票3卖出");
47     }
48 }
49 package facade;
50 
51 /**
52  * 国债1
53  */
54 public class NationalDebt1 {
55 
56     public void buy() {
57         System.out.println("国债1买入");
58     }
59 
60     public void sell() {
61         System.out.println("国债1卖出");
62     }
63 }
64 package facade;
65 
66 /**
67  * 未使用设计模式
68  */
69 public class Client {
70 
71     public static void main(String[] args) {
72         Stock1 stock1 = new Stock1();
73         Stock2 stock2 = new Stock2();
74         Stock3 stock3 = new Stock3();
75         NationalDebt1 ndt1 = new NationalDebt1();
76 
77         stock1.buy();
78         stock2.buy();
79         stock3.buy();
80         ndt1.buy();
81 
82         stock1.sell();
83         stock2.sell();
84         stock3.sell();
       ndt1.sell();
85 } 86 }
  • 采用外观模式 
package facade;

/**
 * 基金
 */
public class Fund {

    private Stock1 stock1;
    private Stock2 stock2;
    private Stock3 stock3;
    private NationalDebt1 ndt1;

    public Fund() {
        stock1 = new Stock1();
        stock2 = new Stock2();
        stock3 = new Stock3();
        ndt1 = new NationalDebt1();
    }

    public void buy(){
        stock1.buy();
        stock2.buy();
        stock3.buy();
        ndt1.buy();
    }

    public void sell(){
        stock1.sell();
        stock2.sell();
        stock3.sell();
        ndt1.sell();
    }
}
package facade;

/**
 * 外观模式使用的客户端
 */
public class FacadeClient {

    public static void main(String[] args) {
        Fund fund = new Fund();
        fund.buy();
        fund.sell();
    }
}
  • 外观模式的使用
    • 在 java.util.logging包中使用到了
    • JDBC封装后的,commons提供的DBUtils类
    • Hibernate提供的工具类、SpringJDBC工具类等
原文地址:https://www.cnblogs.com/huangyichun/p/7106183.html