Facade 模式解说 我们平时的开发中其实已经不知不觉的在用 Façade 模式,现在来考虑这样一个抵押系统,当有一个客户来时,有如下几件事情需要确认:到银行子系统查询他是否有足够多的存款,到信用子系统查询他是否有良好的信用,到贷款子系统查询他有无贷款劣迹。只有这三个子系统都通过时才可进行抵押。我们先不考虑 Façade 模式,那么客户程序就要直接访问这些子系统,分别进行判断。类结构图下: 图 3 在这个程序中,我们首先要有一个顾客类,它是一个纯数据类,并无任何操作,示意代码:
// 顾客类 public class Customer { private string _name; public Customer( string name) { this ._name = name; } public string Name { get { return _name; } } } 下面这三个类均是子系统类,示意代码: // 银行子系统 public class Bank { public bool HasSufficientSavings(Customer c, int amount) { Console.WriteLine( " Check bank for " + c.Name); return true ; } } // 信用子系统 public class Credit { public bool HasGoodCredit(Customer c) { Console.WriteLine( " Check credit for " + c.Name); return true ; } } // 贷款子系统 public class Loan { public bool HasNoBadLoans(Customer c) { Console.WriteLine( " Check loans for " + c.Name); return true ; } } 来看客户程序的调用: Façade 模式的情况下,客户程序与三个子系统都发生了耦合,这种耦合使得客户程序依赖于子系统,当子系统变化时,客户程序也将面临很多变化的挑战。一个合情合理的设计就是为这些子系统创建一个统一的接口,这个接口简化了客户程序的判断操作。看一下引入 Façade 模式后的类结构图: // 客户程序 public class MainApp { private const int _amount = 12000 ; public static void Main() { Bank bank = new Bank(); Loan loan = new Loan(); Credit credit = new Credit(); Customer customer = new Customer( " Ann McKinsey " ); bool eligible = true ; if ( ! bank.HasSufficientSavings(customer, _amount)) { eligible = false ; } else if ( ! loan.HasNoBadLoans(customer)) { eligible = false ; } else if ( ! credit.HasGoodCredit(customer)) { eligible = false ; } Console.WriteLine( " /n " + customer.Name + " has been " + (eligible ? " Approved " : " Rejected " )); Console.ReadLine(); } } 可以看到,在不用 图 4 门面类 Mortage 的实现如下: // 外观类 public class Mortgage { private Bank bank = new Bank(); private Loan loan = new Loan(); private Credit credit = new Credit(); public bool IsEligible(Customer cust, int amount) { Console.WriteLine( " {0} applies for {1:C} loan/n " , cust.Name, amount); bool eligible = true ; if ( ! bank.HasSufficientSavings(cust, amount)) { eligible = false ; } else if ( ! loan.HasNoBadLoans(cust)) { eligible = false ; } else if ( ! credit.HasGoodCredit(cust)) { eligible = false ; } return eligible; } } 顾客类和子系统类的实现仍然如下: // 银行子系统 public class Bank { public bool HasSufficientSavings(Customer c, int amount) { Console.WriteLine( " Check bank for " + c.Name); return true ; } } // 信用证子系统 public class Credit { public bool HasGoodCredit(Customer c) { Console.WriteLine( " Check credit for " + c.Name); return true ; } } // 贷款子系统 public class Loan { public bool HasNoBadLoans(Customer c) { Console.WriteLine( " Check loans for " + c.Name); return true ; } } // 顾客类 public class Customer { private string name; public Customer( string name) { this .name = name; } public string Name { get { return name; } } } 而此时客户程序的实现: Façade 模式后,客户程序只与 Mortgage 发生依赖,也就是 Mortgage 屏蔽了子系统之间的复杂的操作,达到了解耦内部子系统与客户程序之间的依赖。 // 客户程序类 public class MainApp { public static void Main() { // 外观 Mortgage mortgage = new Mortgage(); Customer customer = new Customer( " Ann McKinsey " ); bool eligable = mortgage.IsEligible(customer, 125000 ); Console.WriteLine( " /n " + customer.Name + " has been " + (eligable ? " Approved " : " Rejected " )); Console.ReadLine(); } } 可以看到引入
.NET 架构中的 Façade 模式 Façade 模式在实际开发中最多的运用当属开发 N 层架构的应用程序了,一个典型的 N 层结构如下: 图 5 在这个架构中,总共分为四个逻辑层,分别为:用户层 UI ,业务外观层 Business Façade ,业务规则层 Business Rule ,数据访问层 Data Access 。其中 Business Façade 层的职责如下: l 从“用户”层接收用户输入 l 如果请求需要对数据进行只读访问,则可能使用“数据访问”层 l 将请求传递到“业务规则”层 l 将响应从“业务规则”层返回到“用户”层 l 在对“业务规则”层的调用之间维护临时状态 对这一架构最好的体现就是 Duwamish 示 例了。在该应用程序中,有部分操作只是简单的从数据库根据条件提取数据,不需要经过任何处理,而直接将数据显示到网页上,比如查询某类别的图书列表。而另 外一些操作,比如计算定单中图书的总价并根据顾客的级别计算回扣等等,这部分往往有许多不同的功能的类,操作起来也比较复杂。如果采用传统的三层结构,这 些商业逻辑一般是会放在中间层,那么对内部的这些大量种类繁多,使用方法也各异的不同的类的调用任务,就完全落到了表示层。这样势必会增加表示层的代码 量,将表示层的任务复杂化,和表示层只负责接受用户的输入并返回结果的任务不太相称,并增加了层与层之间的耦合程度。于是就引入了一个 Façade 层,让这个 Facade 来负责管理系统内部类的调用,并为表示层提供了一个单一 而简单的接口。看一下Duwamish结构图: 图6 从图中可以看到,UI层 将请求发送给业务外观层,业务外观层对请求进行初步的处理,判断是否需要调用业务规则层,还是直接调用数据访问层获取数据。最后由数据访问层访问数据库并按 照来时的步骤返回结果到 UI 层,来看具体的代码实现。 在获取商品目录的时候, Web UI 调用业务外观层:
productSystem = new ProductSystem(); categorySet = productSystem.GetCategories(categoryID); 业务外观层直接调用了数据访问层: public CategoryData GetCategories( int categoryId) { // // Check preconditions // ApplicationAssert.CheckCondition(categoryId >= 0 , " Invalid Category Id " ,ApplicationAssert.LineNumber); // // Retrieve the data // using (Categories accessCategories = new Categories()) { return accessCategories.GetCategories(categoryId); } } 在添加订单时,UI调用业务外观层: public void AddOrder() { ApplicationAssert.CheckCondition(cartOrderData != null , " Order requires data " , ApplicationAssert.LineNumber); // Write trace log. ApplicationLog.WriteTrace( " Duwamish7.Web.Cart.AddOrder:/r/nCustomerId: " + cartOrderData.Tables[OrderData.CUSTOMER_TABLE].Rows[ 0 ][OrderData.PKID_FIELD].ToString()); cartOrderData = ( new OrderSystem()).AddOrder(cartOrderData); } 业务外观层调用业务规则层: public OrderData AddOrder(OrderData order) { // // Check preconditions // ApplicationAssert.CheckCondition(order != null , " Order is required " , ApplicationAssert.LineNumber); ( new BusinessRules.Order()).InsertOrder(order); return order; } 业务规则层进行复杂的逻辑处理后,再调用数据访问层: public bool InsertOrder(OrderData order) { // // Assume it's good // bool isValid = true ; // // Validate order summary // DataRow summaryRow = order.Tables[OrderData.ORDER_SUMMARY_TABLE].Rows[ 0 ]; summaryRow.ClearErrors(); if (CalculateShipping(order) != (Decimal)(summaryRow[OrderData.SHIPPING_HANDLING_FIELD])) { summaryRow.SetColumnError(OrderData.SHIPPING_HANDLING_FIELD, OrderData.INVALID_FIELD); isValid = false ; } if (CalculateTax(order) != (Decimal)(summaryRow[OrderData.TAX_FIELD])) { summaryRow.SetColumnError(OrderData.TAX_FIELD, OrderData.INVALID_FIELD); isValid = false ; } // // Validate shipping info // isValid &= IsValidField(order, OrderData.SHIPPING_ADDRESS_TABLE, OrderData.SHIP_TO_NAME_FIELD, 40 ); // // Validate payment info // DataRow paymentRow = order.Tables[OrderData.PAYMENT_TABLE].Rows[ 0 ]; paymentRow.ClearErrors(); isValid &= IsValidField(paymentRow, OrderData.CREDIT_CARD_TYPE_FIELD, 40 ); isValid &= IsValidField(paymentRow, OrderData.CREDIT_CARD_NUMBER_FIELD, 32 ); isValid &= IsValidField(paymentRow, OrderData.EXPIRATION_DATE_FIELD, 30 ); isValid &= IsValidField(paymentRow, OrderData.NAME_ON_CARD_FIELD, 40 ); isValid &= IsValidField(paymentRow, OrderData.BILLING_ADDRESS_FIELD, 255 ); // // Validate the order items and recalculate the subtotal // DataRowCollection itemRows = order.Tables[OrderData.ORDER_ITEMS_TABLE].Rows; Decimal subTotal = 0 ; foreach (DataRow itemRow in itemRows) { itemRow.ClearErrors(); subTotal += (Decimal)(itemRow[OrderData.EXTENDED_FIELD]); if ((Decimal)(itemRow[OrderData.PRICE_FIELD]) <= 0 ) { itemRow.SetColumnError(OrderData.PRICE_FIELD, OrderData.INVALID_FIELD); isValid = false ; } if (( short )(itemRow[OrderData.QUANTITY_FIELD]) <= 0 ) { itemRow.SetColumnError(OrderData.QUANTITY_FIELD, OrderData.INVALID_FIELD); isValid = false ; } } // // Verify the subtotal // if (subTotal != (Decimal)(summaryRow[OrderData.SUB_TOTAL_FIELD])) { summaryRow.SetColumnError(OrderData.SUB_TOTAL_FIELD, OrderData.INVALID_FIELD); isValid = false ; } if ( isValid ) { using (DataAccess.Orders ordersDataAccess = new DataAccess.Orders()) { return (ordersDataAccess.InsertOrderDetail(order)) > 0 ; } } else return false ; } [MSDN]
效果及实现要点 1 . Façade 模式对客户屏蔽了子系统组件,因而减少了客户处理的对象的数目并使得子系统使用起来更加方便。 2 . Façade 模式实现了子系统与客户之间的松耦合关系,而子系统内部的功能组件往往是紧耦合的。松耦合关系使得子系统的组件变化不会影响到它的客户。 3 .如果应用需要,它并不限制它们使用子系统类。因此你可以在系统易用性与通用性之间选择。
适用性 1 .为一个复杂子系统提供一个简单接口。 2 .提高子系统的独立性。 3 .在层次化结构中,可以使用 Facade 模式定义系统中每一层的入口。
总结 Façade 模式注重的是简化接口,它更多的时候是从架构的层次去看整个系统,而并非单个类的层次。
参考资料 Erich Gamma 等,《设计模式:可复用面向对象软件的基础》,机械工业出版社 Robert C.Martin ,《敏捷软件开发:原则、模式与实践》,清华大学出版社 阎宏,《 Java 与模式》,电子工业出版社 Alan Shalloway James R. Trott ,《 Design Patterns Explained 》,中国电力出版社 MSDN WebCast 《 C# 面向对象设计模式纵横谈 (11) : Facade 外观模式 ( 结构型模式 ) 》