外觀模式為子系統一群介面提供統一介面,定義高層介面讓子系統更易使用。屬於結構型模式。
MethodA()、MethodB() 等高層操作
// 子系統
public class SubSystemOne { public void MethodOne() => Console.WriteLine("子系統 One 方法"); }
public class SubSystemTwo { public void MethodTwo() => Console.WriteLine("子系統 Two 方法"); }
public class SubSystemThree { public void MethodThree() => Console.WriteLine("子系統 Three 方法"); }
// Facade
public class Facade {
SubSystemOne one = new SubSystemOne();
SubSystemTwo two = new SubSystemTwo();
SubSystemThree three = new SubSystemThree();
public void MethodA() {
Console.WriteLine("開始 MethodA"); one.MethodOne(); two.MethodTwo(); Console.WriteLine("MethodA 結束");
}
public void MethodB() {
Console.WriteLine("開始 MethodB"); two.MethodTwo(); three.MethodThree(); Console.WriteLine("MethodB 結束");
}
}
// Client
static void Main() { new Facade().MethodA(); new Facade().MethodB(); }
功能:驗證課程名額、收費、通知用戶。子系統:
PaymentGateway:ChargeStudent(name, cost)RegisterCourse:CheckAvailability(courseCode)、GetTuitionCost(courseCode)NotifyUser:Notify(studentName)RegistrationFacade 封裝完整流程:
public class RegistrationFacade {
PaymentGateway _pg = new PaymentGateway();
RegisterCourse _rc = new RegisterCourse();
NotifyUser _nu = new NotifyUser();
public bool RegisterStudent(string course, string student) {
if (!_rc.CheckAvailability(course)) return false;
if (!_pg.ChargeStudent(student, _rc.GetTuitionCost(course))) return false;
return _nu.Notify(student);
}
}
// Client
var facade = new RegistrationFacade();
if (facade.RegisterStudent("DesignPatterns101", "Jane Doe"))
Console.WriteLine("註冊成功!");
外觀模式提供統一高層介面,有效解決分層解耦、降低耦合、新舊系統整合三大問題,是企業級應用架構常用模式。