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

C語言介面與實作分離設計模式實戰範例

     編輯:關於C

模組設計:介面與實作分離

模組包含介面(宣告功能)與實作(具體演算法/資料結構)。介面隱藏細節以降低耦合,實作可多樣化但需符合介面契約。C語言透過頭檔(.h)宣告介面,.c 提供實作,客戶端 #include 介面,實作 #include 介面確保一致性。

範例 1:算術運算介面 Arith

介面 arith.h

#ifndef ARITH_H
#define ARITH_H

int Arith_max(int x, int y);
int Arith_min(int x, int y);
int Arith_div(int x, int y);   // 向負無窮取整除法
int Arith_mod(int x, int y);   // 對應餘數:x - y * Arith_div(x,y)
int Arith_ceiling(int x, int y); // 不小於商的最小整數
int Arith_floor(int x, int y);   // 不超過商的最大整數

#endif

介面名 Arith 作為前綴避免命名衝突。提供標準庫缺失的良好定義除法/取模語義(標準 C 向零取整,實作相關)。

實作 arith.c

#include "arith.h"

int Arith_max(int x, int y) { return x > y ? x : y; }
int Arith_min(int x, int y) { return x > y ? y : x; }

int Arith_div(int x, int y) {
    int q = x / y, r = x % y;
    if (r != 0 && ((r > 0) != (y > 0))) q--;  // 向負無窮調整
    return q;
}
int Arith_mod(int x, int y) { return x - y * Arith_div(x, y); }
int Arith_ceiling(int x, int y) { return -Arith_div(-x, y); }
int Arith_floor(int x, int y) { return Arith_div(x, y); }

範例 2:抽象資料型別(ADT)— 堆疊 Stack

介面 stack.h

#ifndef STACK_H
#define STACK_H

typedef struct Stack_T *Stack_T;  // 不透明指標,隱藏內部結構

Stack_T Stack_new(void);
int Stack_empty(Stack_T stk);
void Stack_push(Stack_T stk, void *x);
void *Stack_pop(Stack_T stk);
void Stack_free(Stack_T *stk);

#endif

實作 stack.c

#include <stddef.h> #include <assert.h> #include "mem.h" #include "stack.h"

#define T Stack_T

struct T {
    int count;
    struct elem { void *x; struct elem *link; } *head;
};

T Stack_new(void) {
    T stk; NEW(stk);  // NEW 為 mem.h 巨集:分配並指派
    stk->count = 0; stk->head = NULL;
    return stk;
}

int Stack_empty(T stk) { assert(stk); return stk->count == 0; }

void Stack_push(T stk, void *x) {
    assert(stk);
    struct elem *t; NEW(t);
    t->x = x; t->link = stk->head; stk->head = t; stk->count++;
}

void *Stack_pop(T stk) {
    assert(stk && stk->count > 0);
    struct elem *t = stk->head;
    stk->head = t->link; stk->count--;
    void *x = t->x; FREE(t); return x;  // FREE 釋放並置 NULL
}

void Stack_free(T *stk) {
    assert(stk && *stk);
    for (struct elem *t = (*stk)->head, *u; t; t = u) {
        u = t->link; FREE(t);
    }
    FREE(*stk);
}

設計精要總結

  • 不透明指標: 介面僅宣告 typedef struct T *T;,實作定義 struct T,客戶端完全看不見內部欄位。
  • 斷言防禦: assert 捕捉空指標、前置條件違反,屬可檢查執行期錯誤。
  • 記憶體管理介面: NEW/FREE 巨集封裝分配/釋放邏輯,實作與介面解耦。
  • 泛型設計: 以 void* 儲存任意型別資料,配合函式指標可擴展為型別安全容器。
  • 單一職責: 介面定義「做什麼」,實作決定「怎麼做」,修改實作不影響客戶端。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved