2.4 方向
方向是AspectC++的語言元素用來收集以模塊化的方法實(shí)現(xiàn)共同橫切關(guān)注的引入和建議代碼的。這將方向置于管理共同狀態(tài)信息的位置。它們由不同的方向聲明聲明構(gòu)成,作為C++類概念的擴(kuò)展?;镜姆较蚵暶鹘Y(jié)構(gòu)和常見的C++定義完全一樣,除了使用關(guān)鍵詞aspect代替了class,struct或者union?;诖?,方向可以有許多屬性、方法,并且可以繼承自多個類甚至其它的方向。
例:方向聲明
aspect Counter {
static int m_count;
pointcut counted() = "Circle" || "Polygon";
advice counted() : slice struct {
class Helper {
Helper() { Counter::m_count++; }
} m_counter;
}
advice execution("% main(...)") : after() {
cout << "Final count: " << m_count << " objects" << endl;
}
};
... and at an appropriate place
#include "Counter.ah"
int Counter::m_count = 0;
在這個例子中,一系列類的對象實(shí)例數(shù)量被限定了。因此,在點(diǎn)切描述的類中引入屬性m_counter將在實(shí)例構(gòu)造時增加全局計(jì)數(shù)器。通過對main函數(shù)應(yīng)用建議代碼,當(dāng)程序中止后最終的對象實(shí)例將會展示出來。
這個例子也可以用抽象方向重寫這樣就可以為了復(fù)用歸檔成一個方向庫。它只需要重新實(shí)現(xiàn)點(diǎn)切聲明來成為純虛。
例:抽象方向
aspect Counter {
static int m_count;
Counter() : m_count(0) {}
pointcut virtual counted() = 0;
...
};
它現(xiàn)在可以繼承自Counter,能過程序化重新實(shí)現(xiàn)counted來指代真正的點(diǎn)切表達(dá)式。
例:復(fù)用抽象方向
aspect MCounter : public Counter {
pointcut counted() = derived("Shape");
};
2.4.1 方向安裝
默認(rèn)情況下,AspectC++中的方向是自動安裝為全局對象的。其背后的設(shè)計(jì)理由是方向也可以提供全局程序?qū)傩?,因此總是可以訪問的。然而在一些特殊的案例下,可能需要改變這種表現(xiàn)行為。例如,在操作系統(tǒng)上下文中,方向應(yīng)該安裝到每個進(jìn)程或者線程中。
可以通過分別定義靜態(tài)方法aspectof來改變默認(rèn)的安裝模式。aspectOf在其他方面生成一個方向。這個方法應(yīng)該總是可以返回一個合適的方向的實(shí)例。
**例:使用aspectof安裝方向
aspect ThreadCounter : public Counter {
pointcut counted() = "Thread";
advice counted() : ThreadCounter m_instance;
static ThreadCounter *aspectof() {
return tjp->target()->m_instance;
}
};
向Thread中引入m_instance保證了每個線程對象有這個方向的一個實(shí)例。通過調(diào)用aspectof,可以在任意結(jié)合點(diǎn)獲得這個實(shí)例,這對于訪問建議代碼和對象成員是十分關(guān)鍵的。出于這個原因,aspectof中的代碼通過下一節(jié)描述的方法獲得訪問真正結(jié)合點(diǎn)的全部權(quán)限。