首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

.NET 設計模式實戰:外觀模式完整解析與遠程教學註冊系統案例

     編輯:關於.NET

模式簡介

外觀模式為子系統一群介面提供統一介面,定義高層介面讓子系統更易使用。屬於結構型模式。

解決問題

  1. 分層解耦:如三層架構中表現層、業務層、資料層分離
  2. 降低依賴:系統複雜度增長時,提供簡單介面減少相依
  3. 新舊系統整合:舊系統難維護,新系統透過 Facade 與之互動,封裝複雜邏輯

結構角色

  • SubSystemA/B/C:子系統類別,各自實作特定功能
  • Facade:外觀類別,組合子系統,提供 MethodA()、MethodB() 等高層操作
  • Client:僅呼叫 Facade
外觀模式結構圖

基礎實作

// 子系統
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("註冊成功!");
註冊系統結構圖

總結

外觀模式提供統一高層介面,有效解決分層解耦、降低耦合、新舊系統整合三大問題,是企業級應用架構常用模式。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved