.NET设计模式(12):外观模式(Façade Pattern)
外观模式(Façade Pattern)
意图
图
1 Façade
模式示意性对象图
图
2
使用电话订货例子的外观模式对象图
图
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;
}
}
来看客户程序的调用:
//
客户程序
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();
}
}
可以看到,在不用 Façade 模式的情况下,客户程序与三个子系统都发生了耦合,这种耦合使得客户程序依赖于子系统,当子系统变化时,客户程序也将面临很多变化的挑战。一个合情合理的设计就是为这些子系统创建一个统一的接口,这个接口简化了客户程序的判断操作。看一下引入 Façade 模式后的类结构图:
图
4
//
外观类
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; }
}
}
而此时客户程序的实现:
//
客户程序类
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();
}
}
可以看到引入 Façade 模式后,客户程序只与 Mortgage 发生依赖,也就是 Mortgage 屏蔽了子系统之间的复杂的操作,达到了解耦内部子系统与客户程序之间的依赖。
图
5
图6
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;
}