C++ ISP Interface Segregation Princlple示例

本例將care_taker程序拆分為兩個單獨的care_taker對象,一個是sunlight_care_taker_t, 一個是moisture_care_taker_t。
本例采用C++的命名空間機制進行了分層。同時采用python的下劃線命名法。
程序的目錄結(jié)構(gòu)如下


圖片.png

完整的代碼如下,
https://gitlab.com/zhuge20100104/cpp_practice/-/tree/master/solid_cpp/02_plant_care_isp?ref_type=heads

CMakeLists.txt

cmake_minimum_required(VERSION 3.3)

project(02_plant_care_isp)

set(ENV{PKG_CONFIG_PATH} "$ENV{PKG_CONFIG_PATH}:/usr/local/lib/pkgconfig/")

set ( CMAKE_CXX_FLAGS "-pthread")
set(CMAKE_CXX_STANDARD 20)
add_definitions(-g)

include_directories(
    ${INCLUDE_DIRS}
    ${CMAKE_CURRENT_SOURCE_DIR}/include
)

LINK_DIRECTORIES(${LINK_DIRS})

file( GLOB main_file_list ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp) 
file( GLOB SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/**/**/*.cc)

foreach( main_file ${main_file_list} )
    file(RELATIVE_PATH filename ${CMAKE_CURRENT_SOURCE_DIR} ${main_file})
    string(REPLACE ".cpp" "" file ${filename})
    add_executable(${file}  ${main_file} ${SOURCES})
    target_link_libraries(${file} pthread)
endforeach( main_file ${main_file_list})

main.cpp

#include <thread>
#include <mutex>
#include "care_taker/moisture_care_taker.h"
#include "care_taker/sunlight_care_taker.h"
#include "sensors/moisture_sensor.h"
#include "sensors/sunlight_sensor.h"

void run() {
    std::mutex sensor_mutex;
    sensors::sunlight_sensor_t sunlight_sensor(std::chrono::seconds(2), sensor_mutex);
    sensors::moisture_sensor_t moisture_sensor(std::chrono::seconds(3), sensor_mutex);

    care_taker::sunlight_care_taker_t sunlight_care_taker;
    care_taker::moisture_care_taker_t moisture_care_taker;
    
    moisture_sensor.subscribe(moisture_care_taker);
    sunlight_sensor.subscribe(sunlight_care_taker);

    std::thread sunlight_sensor_thread(sunlight_sensor);
    std::thread moisture_sensor_thread(moisture_sensor);

    sunlight_sensor_thread.join();
    moisture_sensor_thread.join();
}

int main(int argc, char* argv[]) {
    run();
    return EXIT_SUCCESS;
}

care_taker/i_moisture_care_taker.h

#ifndef _FREDIRC_I_MOISTURE_CARE_TAKER_H_
#define _FREDIRC_I_MOISTURE_CARE_TAKER_H_

namespace care_taker {

class i_moisture_care_taker_t {
public:
    virtual ~i_moisture_care_taker_t() = default;

    virtual void pour_water() = 0;
    virtual void sprinkle_water() = 0;
};

} // namespace care_taker

#endif

care_taker/i_sunlight_care_taker.h

#ifndef _FREDRIC_I_SUNLIGHT_CARE_TAKER_H_
#define _FREDRIC_I_SUNLIGHT_CARE_TAKER_H_

namespace care_taker { 

class i_sunlight_care_taker_t {
public:
    ~i_sunlight_care_taker_t() = default;

    virtual void open_window_blinds() = 0;
    virtual void close_window_blinds() = 0;
};

} // namespace care_taker
#endif

care_taker/moisture_care_taker.h

#ifndef _FREDIRC_MOISTURE_CARE_TAKER_H_
#define _FREDIRC_MOISTURE_CARE_TAKER_H_
#include "care_taker/i_moisture_care_taker.h"

namespace care_taker {

class moisture_care_taker_t: public i_moisture_care_taker_t {
public:
    void pour_water() override;
    void sprinkle_water() override;
};
} // end care_taker
#endif

care_taker/sunlight_care_taker.h

#ifndef _FREDRIC_SUNLIGHT_CARE_TAKER_H_
#define _FREDRIC_SUNLIGHT_CARE_TAKER_H_

#include "care_taker/i_sunlight_care_taker.h"

namespace care_taker { 

class sunlight_care_taker_t: public i_sunlight_care_taker_t {
    bool m_window_blinds_open {true};
    
public:
    void open_window_blinds() override;
    void close_window_blinds() override;
};

} // namespace care_taker
#endif

care_taker/moisture_care_taker.cc

#include "care_taker/moisture_care_taker.h"

#include <iostream>

namespace care_taker {

void moisture_care_taker_t::pour_water() {
    std::cout << "pouring water on Aloe" << std::endl;
}

void moisture_care_taker_t::sprinkle_water() {
    std::cout << "sprinkling water on Aloe" << std::endl;
}

}

care_taker/sunlight_care_taker.cc

#include "care_taker/sunlight_care_taker.h"
#include <iostream>

namespace care_taker {

void sunlight_care_taker_t::open_window_blinds() {
    if(!m_window_blinds_open) {
        m_window_blinds_open = true;
        std::cout << "Opened window blinds for Aloe" << std::endl;
    }
}

void sunlight_care_taker_t::close_window_blinds() {
    if(m_window_blinds_open) {
        m_window_blinds_open = false;
        std::cout << "Closed window blinds for Aloe" << std::endl;
    }
}

}

sensors/moisture_sensor.h

#ifndef _FREDRIC_MOISTURE_SENSOR_H_
#define _FREDRIC_MOISTURE_SENSOR_H_
#include <chrono>
#include <mutex>
#include <set>

#include "care_taker/i_moisture_care_taker.h"

namespace sensors {

class moisture_sensor_t {
    std::chrono::seconds const m_sleep_time;
    std::mutex& m_mutex;
    std::set<care_taker::i_moisture_care_taker_t*> m_care_takers;
    int const m_min = 0;
    int const m_max = 10;
    int const m_threshold = 3;

public:
    moisture_sensor_t(std::chrono::seconds, std::mutex&);
    void subscribe(care_taker::i_moisture_care_taker_t&);
    void operator()();


private:
    bool is_air_too_dry();
    bool is_soil_too_dry();
    int get_air_moisture();
    int get_soil_moisture();

};

}
#endif

sensors/sunlight_sensor.h

#ifndef _FREDRIC_SUNLIGHT_SENSOR_H_
#define _FREDRIC_SUNLIGHT_SENSOR_H_
#include <chrono>
#include <mutex>
#include <set>
#include <optional>

#include "care_taker/i_sunlight_care_taker.h"

namespace sensors {

class sunlight_sensor_t {
    using time_point_t = decltype(std::chrono::system_clock::now());

    std::chrono::seconds const m_sleep_time;

    std::mutex& m_mutex;
    std::set<care_taker::i_sunlight_care_taker_t*> m_care_takers;

    std::optional<time_point_t> m_sunlight_on_from;
    std::optional<time_point_t> m_sunlight_off_from;

    int const m_thresold = 2;
    bool m_sensor_on = true;

public:
    sunlight_sensor_t(std::chrono::seconds const, std::mutex&);
    void subscribe(care_taker::i_sunlight_care_taker_t&);
    void operator()();

private:
    void update_state(bool const);
    bool is_too_much_sunlight(bool const);
    bool is_too_little_sunlight(bool const);
    bool is_sunlight() const;

};

} // sensors

#endif

sensors/moisture_sensor.cc

#include "sensors/moisture_sensor.h"

#include <thread>
#include <random>

namespace sensors {

moisture_sensor_t::moisture_sensor_t(std::chrono::seconds sleep_time, std::mutex& mutex_):
    m_sleep_time(sleep_time), m_mutex(mutex_) {

}

void moisture_sensor_t::subscribe(care_taker::i_moisture_care_taker_t& care_taker) {
    m_care_takers.insert(&care_taker);
}

void moisture_sensor_t::operator()() {
    for(;;) {
        std::unique_lock<std::mutex> lock(m_mutex);
        if(is_air_too_dry()) {
            for(auto care_taker : m_care_takers) {
                care_taker->sprinkle_water();
            }
        }
        if(is_soil_too_dry()) {
            for(auto care_taker : m_care_takers) {
                care_taker->pour_water();
            }
        }

        lock.unlock();
        std::this_thread::sleep_for(m_sleep_time);
    }
}

bool moisture_sensor_t::is_air_too_dry() {
    return get_air_moisture() < m_threshold;
}

bool moisture_sensor_t::is_soil_too_dry() {
    return get_soil_moisture() < m_threshold;
}

int moisture_sensor_t::get_air_moisture() {
    static std::mt19937 generator;
    return std::uniform_int_distribution<int>(m_min, m_max)(generator);
}

int moisture_sensor_t::get_soil_moisture() {
    static std::mt19937 generator;
    return std::uniform_int_distribution<int>(m_min, m_max)(generator);
}

}

sensors/sunlight_sensor.cc

#include "sensors/sunlight_sensor.h"
#include <iostream>
#include <thread>
#include <random>

namespace sensors {
sunlight_sensor_t::sunlight_sensor_t(std::chrono::seconds const sleep_time, std::mutex& mutex_):
    m_sleep_time{sleep_time},
    m_mutex{mutex_}
{

} 

void sunlight_sensor_t::subscribe(care_taker::i_sunlight_care_taker_t& care_taker) {
    m_care_takers.insert(&care_taker);
}
    
void sunlight_sensor_t::operator()() {
    for(;;) {
        std::unique_lock<std::mutex> lock(m_mutex);
        auto const sunlight = is_sunlight();
        update_state(sunlight);
        std::cout << "sun shines: " << std::boolalpha << sunlight << std::endl;
        if(is_too_much_sunlight(sunlight)) {
            for(auto& p: m_care_takers) {
                p->close_window_blinds();
            }
            m_sensor_on = false;
        } else if(is_too_little_sunlight(sunlight)) {
            for(auto& p: m_care_takers) {
                p->open_window_blinds();
            }
            m_sensor_on = true;
        }
        lock.unlock();
        std::this_thread::sleep_for(m_sleep_time);
    }
}


void sunlight_sensor_t::update_state(bool const sunlight) {
    auto const current_time = std::chrono::system_clock::now();

    if(sunlight && m_sensor_on) {
        m_sunlight_on_from = m_sunlight_on_from? *m_sunlight_on_from: current_time;
        m_sunlight_off_from = std::nullopt;
    } else if(!sunlight) {
        m_sunlight_off_from = m_sunlight_off_from? *m_sunlight_off_from: current_time;
        m_sunlight_on_from = std::nullopt;
    }
}


bool sunlight_sensor_t::is_too_much_sunlight(bool const sunlight) {
    if(sunlight) {
        auto const time_now = std::chrono::system_clock::now();
        std::chrono::duration<double> elapsed_secs = time_now - *m_sunlight_on_from;
        return elapsed_secs.count() > m_thresold;
    }
    return false;
}

bool sunlight_sensor_t::is_too_little_sunlight(bool const sunlight) {
    if(!sunlight) {
        auto const time_now = std::chrono::system_clock::now();
        std::chrono::duration<double> elapsed_secs = time_now - *m_sunlight_off_from;
        return elapsed_secs.count() > m_thresold;
    }
    return false;
}

bool sunlight_sensor_t::is_sunlight() const {
    static bool sun_shines = false;
    static std::mt19937 generator;
    auto prob = std::uniform_int_distribution<int>(1, 100)(generator);
    if(prob >= 80) {
        sun_shines = !sun_shines;
    }

    return sun_shines;
}

}

程序輸出的效果如下,


圖片.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,837評論 6 531
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,196評論 3 414
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,688評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,654評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 71,456評論 6 406
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 54,955評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,044評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,195評論 0 287
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,725評論 1 333
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 40,608評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,802評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,318評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 44,048評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,422評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,673評論 1 281
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,424評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 47,762評論 2 372

推薦閱讀更多精彩內(nèi)容