设计模式:外观模式(Façade Pattern) 明

作者:TerryLee  创建于:2006-03-17 出处:http://terrylee.cnblogs.com/archive/2006/03/17/352349.html  收录于:2013-02-28

示意图


门面模式没有一个一般化的类图描述,下面是一个示意性的对象图:

意图


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

适用性


  • 为一个复杂子系统提供一个简单接口。
  • 提高子系统的独立性。
  • 在层次化结构中,可以使用Facade模式定义系统中每一层的入口。

实现代码


我们平时的开发中其实已经不知不觉的在用Façade模式,现在来考虑这样一个抵押系统,当有一个客户来时,有如下几件事情需要确认:到银行子系统查询他是否有足够多的存款,到信用子系统查询他是否有良好的信用,到贷款子系统查询他有无贷款劣迹。只有这三个子系统都通过时才可进行抵押。

View Code
 1 using System;
 2 //银行子系统
 3 public class Bank
 4 {
 5     public bool HasSufficientSavings(Customer c, int amount)
 6     {
 7         Console.WriteLine("Check bank for " + c.Name);
 8         return true;
 9     }
10 }
11 //信用证子系统
12 public class Credit
13 {
14     public bool HasGoodCredit(Customer c)
15     {
16         Console.WriteLine("Check credit for " + c.Name);
17         return true;
18     }
19 }
20 //贷款子系统
21 public class Loan
22 {
23     public bool HasNoBadLoans(Customer c)
24     {
25         Console.WriteLine("Check loans for " + c.Name);
26         return true;
27     }
28 }
29 //顾客类
30 public class Customer
31 {
32     private string name;
33     public Customer(string name)
34     {
35         this.name = name;
36     }
37     public string Name
38     {
39         get { return name; }
40     }
41 }
42 //外观类
43 public class Mortgage
44 {
45     private Bank bank = new Bank();
46     private Loan loan = new Loan();
47     private Credit credit = new Credit();
48     public bool IsEligible(Customer cust, int amount)
49     {
50         Console.WriteLine("{0} applies for {1:C} loan\n",
51           cust.Name, amount);
52         bool eligible = true;
53         if (!bank.HasSufficientSavings(cust, amount))
54         {
55             eligible = false;
56         }
57         else if (!loan.HasNoBadLoans(cust))
58         {
59             eligible = false;
60         }
61         else if (!credit.HasGoodCredit(cust))
62         {
63             eligible = false;
64         }
65         return eligible;
66     }
67 }
68 //客户程序类
69 public class MainApp
70 {
71     public static void Main()
72     {
73         //外观
74         Mortgage mortgage = new Mortgage();
75         Customer customer = new Customer("Ann McKinsey");
76         bool eligable = mortgage.IsEligible(customer, 125000);
77         Console.WriteLine("\n" + customer.Name +
78             " has been " + (eligable ? "Approved" : "Rejected"));
79         Console.ReadLine();
80     }
81 }

效果及实现要点


1.Façade模式对客户屏蔽了子系统组件,因而减少了客户处理的对象的数目并使得子系统使用起来更加方便。

2.Façade模式实现了子系统与客户之间的松耦合关系,而子系统内部的功能组件往往是紧耦合的。松耦合关系使得子系统的组件变化不会影响到它的客户。
3.如果应用需要,它并不限制它们使用子系统类。因此你可以在系统易用性与通用性之间选择。

原文地址:https://www.cnblogs.com/Ming8006/p/2937360.html