詳解C/C++中低耦合代碼的設(shè)計實現(xiàn)
在我們設(shè)計C/C++ 程序的時候,有時需要兩個類或者兩個模塊相互“認識”,或者兩個模塊間函數(shù)互相調(diào)用,假設(shè)我們正在開發(fā)一個網(wǎng)上商店,代表的網(wǎng)店客戶的類必須要知道相關(guān)的賬戶。
UML圖如下,這被稱為環(huán)依賴,這兩個類直接或間接地相互依賴。

一般我們都會采用結(jié)構(gòu)體或類前置聲明的方式,在解決此問題。
customer.h
#ifndef CUSTOMER_H_
#define CUSTOMER_H_
class Account;
class Customer
{
// ...
void setAccount(Account* account);
{
customerAccount = account;
}
//...
private:
Account* customerAccount;
};
#endifaccount.h
#ifndef ACCOUNT_H_
#define ACCOUNT_H_
class Customer;
class Account
{
public:
//...
void setOwer(Customer* customer)
{
ower = customer;
}
//...
private:
Customer* ower;
}
#endif老實說上面的方式確實可以消除編譯器的錯誤,但是這種解決方案不夠好。
下面的調(diào)用示例,存在一個問題,當(dāng)刪除Account的實例,Customer的實例仍然存在,且內(nèi)部的指向Account的指針為空。使用或解引用此指正會導(dǎo)致嚴(yán)重的問題。
#include "account.h"
#include "customer.h"
//...
Account *account = new Accout{};
Customer *customer = new Customer{};
account->setOwer(customer);
customer->setAccount(account);
那有沒有更好的做法呢,依賴倒置原則可以很好的解決此類問題。
依賴倒置原則
第一步是我們不在兩個類中的其中一個訪問另一個,相反,我們只通過接口進行訪問。我們從Customer中提取Ower的接口,作為示例,Ower接口中聲明一個純虛函數(shù),該函數(shù)必須由此接口類覆蓋。
ower.h
#ifndef OWNER_H_
#define OWNER_H_
#include <memory>
#include <string>
class owner
{
public:
virtual ~owner()=default;
virtual std::string getName() const = 0;
};
using OwnerPtr = std::shared_ptr<Owner>;
#endif
Customer.h
#ifndef CUSTOMER_H_
#define CUSTOMER_H_
#include "Owner.h"
#include "Account.h"
class Customer:public Owner
{
public:
void setAccount(AccountPtr account)
{
customerAccount = account;
}
virtual std::string getName() const override{
//return string
}
private:
Account customerAccount;
};
using CustomerPtr = std::shared_ptr<Customer>;
#endifaccount.h
#ifndef ACCOUNT_H_
#define ACCOUNT_H_
#include "Owner.h"
class Account
{
public:
void setOwner(OwnerPtr owner)
{
this->owner = owner;
}
private:
OwnerPtr owner;
};
using AccountPtr = std::shared_ptr<Account>;現(xiàn)在設(shè)計完發(fā)現(xiàn)這兩個模塊間消除了環(huán)依賴。
C/C++ 通過回調(diào)函數(shù)和信號槽的方式降低模塊的耦合性
為了降低模塊功能代碼的耦合性,我們經(jīng)常采用回調(diào)函數(shù)或者信號槽的方式來聯(lián)系兩個模塊。
回調(diào)函數(shù)的方式:
a.h
#pragma once #ifndef A_H_ #define A_H_ #include <stdio.h> int test(int c); #endif
a.c
#include "a.h"
int test(int c)
{
c = 0x11112;
return c;
}
b.h
#pragma once #ifndef B_H_ #define B_H_ #include <stdio.h> typedef int (*PtrFunA)(int); int testb(PtrFunA, int c); #endif
b.c
#include "b.h"
int testb(PtrFunA a, int c)
{
int ret = a(c);
printf("%d\n", ret);
return ret;
}
main.c
#include <stdio.h>
#include "a.h"
#include "b.h"
int main()
{
testb(test,123);
}
這樣做的好處降低代碼的耦合性,是A模塊的功能代碼只寫在A.C中。B.C的功能代碼只寫在B.C中,改進的后的回調(diào)函數(shù)可以用void*進行傳參,在a.c中對void*進行判斷,這是很多代碼常做的操作。
信號槽的話則更加靈活性和代碼的耦合度再次降低,后期在說,先寫在這了。
以上就是詳解C/C++中低耦合代碼的設(shè)計實現(xiàn)的詳細內(nèi)容,更多關(guān)于C++低耦合代碼的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
基于OpenCV實現(xiàn)的人臉簽到系統(tǒng)源代碼
本文從實際背景和需求出發(fā),采用人臉識別簽到考勤改變了傳統(tǒng)人工檢驗的做法,極大提高了組織效率和辦事能力,這篇文章主要給大家介紹了關(guān)于如何基于OpenCV實現(xiàn)的人臉簽到系統(tǒng)的相關(guān)資料,需要的朋友可以參考下2024-04-04

