sigslot簡(jiǎn)介
轉(zhuǎn)載自:http://www.thecodeway.com/blog/?p=85 在開發(fā)一個(gè)復(fù)雜工程的時(shí)候,經(jīng)常會(huì)遇到這樣一個(gè)問題:整個(gè)系統(tǒng)被分成數(shù)個(gè)模塊,每個(gè)模塊提供有限的功能,由上層調(diào)用組成整個(gè)系統(tǒng),為了保證每個(gè)模塊的獨(dú)立性,我們經(jīng)常會(huì)盡量限制模塊與模塊之間的直接聯(lián)系,比如每個(gè)模塊只提供有限的API或者COM接口,而內(nèi)部實(shí)現(xiàn)則完全封閉起來。
但有的時(shí)候會(huì)出一些設(shè)計(jì)要求,必須能夠使模塊之間能夠直接通訊,而這兩個(gè)模塊往往處于不同的邏輯層次,之間相差甚遠(yuǎn),如何設(shè)計(jì)它們之間的調(diào)用模式使整個(gè)工程維持整潔變得非常困難,比如模塊直接直接包含對(duì)方的頭文件會(huì)引起編譯變得復(fù)雜,提供api或者接口會(huì)引起版本危機(jī)等問題。
sigslot的出現(xiàn)為我們提供了一種解決問題的思想,它用“信號(hào)”的概念實(shí)現(xiàn)不同模塊之間的傳輸問題,sigslot本身類似于一條通訊電纜,兩端提供發(fā)送器和接收器,只要把兩個(gè)模塊用這條電纜連接起來就可以實(shí)現(xiàn)接口調(diào)用,而sigslot本身只是一個(gè)輕量級(jí)的作品,整個(gè)庫只有一個(gè).h文件,所以無論處于何種層次的庫,都可以非常方便的包含它。
舉個(gè)例子,我們?cè)O(shè)計(jì)一個(gè)發(fā)送消息的類,這個(gè)類負(fù)責(zé)在某種時(shí)刻向外界發(fā)出求救信號(hào)
// Class that sends the notification.
class Sender 

{
public:
// The signal declaration.
// The ‘2′ in the name indicates the number of parameters. Parameter types
// are declared in the template parameter list.
sigslot::signal2< std::string , int > SignalDanger;
// When anyone calls Panic(), we will send the SignalDanger signal.
void Panic()
{
SignalDanger("Help!", 0);
}
};
另外一個(gè)類則負(fù)責(zé)接收求助信號(hào)
// Listening class. It must inherit sigslot.
class Receiver : public sigslot::has_slots<>

{
public:
// When anyone calls Panic(), Receiver::OnDanger gets the message.
// Notice that the number and type of parameters match
// those in Sender::SignalDanger, and that it doesn’t return a value.
void OnDanger(std::string message, int time)
{
printf("I heard something like \"%s\" at %d!\n", message.c_str(), time);
}
};
現(xiàn)在讓我們?cè)谥鬟壿嬛邪堰@兩個(gè)類連接起來
Sender sender;
Receiver receiver;
// Receiver registers to get SignalDanger signals.
// When SignalDanger is sent, it is caught by OnDanger().
// Second parameter gives address of the listener function class definition.
// First parameter points to instance of this class to receive notifications.
sender.SignalDanger.connect(&receiver, Receiver::OnDanger);
只要在任何時(shí)候調(diào)用 sender.Panic()函數(shù),就會(huì)把求救信號(hào)發(fā)送給接收者,而且這兩個(gè)發(fā)送和接收端的模塊都可以獨(dú)立編譯,不會(huì)出現(xiàn)版本問題。
posted on 2010-02-24 20:21 楊粼波 閱讀(1221) 評(píng)論(1) 編輯 收藏 引用

