外观模式

概述:

在软件开发系统中,客户程序经常会与复杂系统的内部子系统之间产生耦合,而导致客户程序随着子系统的变化而变化。那么如何简化客户程序与子系统之间的交互接口?如何将复杂系统的内部子系统与客户程序之间的依赖解耦?这就是要说的Façade 模式。


意图:

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

[csharp] view plaincopy
  1. public class Customer
  2. {
  3. private string name;
  4. public Customer(string name)
  5. {
  6. this.name = name;
  7. }
  8. public string Name
  9. {
  10. get
  11. {
  12. return this.name;
  13. }
  14. }
  15. }
  16. /// <summary>
  17. /// 银行子系统
  18. /// </summary>
  19. public class Bank
  20. {
  21. public bool HasSufficientSavings(Customer c, int amount)
  22. {
  23. Console.WriteLine("Check bank for " + c.Name);
  24. return true;
  25. }
  26. }
  27. /// <summary>
  28. /// 信用子系统
  29. /// </summary>
  30. public class Credit
  31. {
  32. public bool HasGoodCredit(Customer c)
  33. {
  34. Console.WriteLine("Check credit for " + c.Name);
  35. return true;
  36. }
  37. }
  38. /// <summary>
  39. /// 贷款子系统
  40. /// </summary>
  41. public class Loan
  42. {
  43. public bool HasNoBadLoans(Customer c)
  44. {
  45. Console.WriteLine("Check loans for " + c.Name);
  46. return true;
  47. }
  48. }
  49. /// <summary>
  50. /// 外观类,这样客户端不必直接与子系统bank、load和credit class关联,而直接通过外观类来抵押贷款。
  51. /// </summary>
  52. public class FacadeClass
  53. {
  54. private Bank bank = new Bank();
  55. private Loan loan = new Loan();
  56. private Credit credit = new Credit();
  57. public bool IsEligible(Customer cust, int amount)
  58. {
  59. Console.WriteLine("{0} applies for {1:C} loan\n",
  60. cust.Name, amount);
  61. bool eligible = true;
  62. if (!bank.HasSufficientSavings(cust, amount))
  63. {
  64. eligible = false;
  65. }
  66. else if (!loan.HasNoBadLoans(cust))
  67. {
  68. eligible = false;
  69. }
  70. else if (!credit.HasGoodCredit(cust))
  71. {
  72. eligible = false;
  73. }
  74. return eligible;
  75. }
  76. }


效果及实现要点

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

2.Façade模式实现了子系统与客户之间的松耦合关系,而子系统内部的功能组件往往是紧耦合的。松耦合关系使得子系统的组件变化不会影响到它的客户。

3.如果应用需要,它并不限制它们使用子系统类。因此你可以在系统易用性与通用性之间选择。

适用性

1.为一个复杂子系统提供一个简单接口。

2.提高子系统的独立性。

3.在层次化结构中,可以使用Facade模式定义系统中每一层的入口。

总结

Façade模式注重的是简化接口,它更多的时候是从架构的层次去看整个系统,而并非单个类的层次。

posted @ 2013-08-11 13:47  ZWmaqing  阅读(472)  评论(1)    收藏  举报