下面这三个类均是子系统类,示意代码:
来看客户程序的调用://银行子系统 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(); } }