Like Share Discussion Bookmark Smile

J.J. Huang   2025-06-14   Getting Started Golang 07.套件   瀏覽次數:次   DMCA.com Protection Status

Go | 套件實現程式碼的解耦

💬 簡介

當專案逐漸龐大時,將功能模組獨立包裝成套件,是實現解耦(decoupling)高內聚低耦合的核心關鍵。
Go 語言本身即以套件(package)為基本模組單位,善用套件能讓你的架構如魚得水、靈活優雅。

本篇將說明套件在模組化設計中的角色與實作方式,如何分離邏輯、減少依賴、提升維護性。

圖片來源:Gophers


🔍 何謂程式碼解耦?

解耦指的是讓模組彼此間的依賴變得鬆散,各自獨立、互不干涉。

  • ✅ 好處包括:
    • 功能模組可重複使用
    • 容易單元測試
    • 變更風險降至最低
    • 架構彈性與可擴充性提升

套件正是 Go 中達成這些目標的主要工具。


❓ 套件如何幫助解耦?

  • 1️⃣ 功能拆分,單一責任原則

    每個套件專注一個單一職責,如 loggerdbauth,避免交叉依賴與邏輯糾纏。

  • 2️⃣ 隱藏內部實作,僅暴露介面

    透過小寫命名私有內容(不可被其他套件引用),控制資料存取界線。

  • 3️⃣ 搭配介面設計,弱化耦合關係

    使用 interface 定義依賴關係,讓套件之間只認識對方的行為,而非具體實作。


📂 範例專案結構

1
2
3
4
5
6
7
8
project/
├── main.go
├── service/
│ └── payment/
│ ├── processor.go
├── infra/
│ └── stripe/
│ └── gateway.go
  • payment:套件定義支付邏輯,不直接依賴 Stripe 的實作。
  • stripe:套件實作具體支付邏輯,透過介面注入至 payment。
  • 📐 定義解耦的介面層

    • service/payment/processor.go

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      package payment

      type Gateway interface {
      Pay(amount int) error
      }

      type Processor struct {
      gateway Gateway
      }

      func NewProcessor(g Gateway) *Processor {
      return &Processor{gateway: g}
      }

      func (p *Processor) Execute(amount int) error {
      return p.gateway.Pay(amount)
      }

      📝 Processor 不知道實作的細節,只依賴 Gateway 介面。

  • ⚙️ 實作具體邏輯

    • infra/stripe/gateway.go

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      package stripe

      import "fmt"

      type StripeGateway struct{}

      func New() *StripeGateway {
      return &StripeGateway{}
      }

      func (s *StripeGateway) Pay(amount int) error {
      fmt.Println("使用 Stripe 支付金額:", amount)
      return nil
      }
  • 🚀 將實作注入使用

    • main.go

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      package main

      import (
      "project/infra/stripe"
      "project/service/payment"
      )

      func main() {
      gateway := stripe.New()
      processor := payment.NewProcessor(gateway)
      processor.Execute(100)
      }
    • 執行結果:
      1
      使用 Stripe 支付金額: 100

👍 優點解析

解耦技巧 具體效果
使用介面抽象依賴 可以自由替換實作,如改用 PayPal、Mock 等
單向依賴流向 上層邏輯不依賴具體實作層,降低耦合
測試更簡單 可注入 mock 實作進行單元測試

🎯 總結

透過合理設計套件與介面抽象,我們能實現程式碼真正的鬆耦合與高模組化:

  • ✅ 套件劃分功能邏輯
  • ✅ 介面隔離實作細節
  • ✅ 主流程只關心行為,不關心實作
  • ✅ 輕鬆測試、替換、維護

最後建議回顧一下 Go | 菜鳥教學 目錄,了解其章節內容。


註:以上參考了
Go