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

C++ 純虛函數實現協議/委托模式:鬧鐘喚醒人範例

     編輯:關於C++

背景

C++ 無 interface/delegate 關鍵字,但可用純虛函數 + 多重繼承模擬協議委托。

範例:鬧鐘喚醒人

  • Awakable 協議:純虛類,聲明 beAwaken()。
  • AlarmClock:持有 Awakable* delegate,定時後調用 delegate->beAwaken()。
  • Person:繼承 Awakable,實現 beAwaken(),設置鬧鐘時將 this 作為 delegate 傳入。

代碼實現

#include <iostream>
#include <unistd.h>
using namespace std;

class Awakable { public: virtual void beAwaken() = 0; };

class AlarmClock {
public:
    Awakable* delegate;
    void alarmAfter(int seconds) const {
        sleep(seconds);
        cout << "叮咚 叮咚 叮咚" << endl;
        delegate->beAwaken();
    }
};

class Person : public Awakable {
public:
    void rollClock(int seconds) {
        cout << "人設置了鬧鐘 " << seconds << " 秒後響鈴" << endl;
        AlarmClock ac;
        ac.delegate = this;
        ac.alarmAfter(seconds);
    }
    void beAwaken() override { cout << "人被鬧鐘喚醒了" << endl; }
};

int main() {
    Person* person = new Person;
    person->rollClock(5);
    delete person;
    return 0;
}

延伸

Java 用 interface,C# 用 delegate,Objective-C/Swift 用 protocol,函數式語言用 lambda/函數對象。C++ 亦可用 std::function/仿函數實現類似回調。

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