3 回答

TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超7個(gè)贊
AOP解決了橫切關(guān)注點(diǎn)的問(wèn)題,橫切關(guān)注點(diǎn)可能是在不同方法中重復(fù)的任何類(lèi)型的代碼,通常無(wú)法像日志記錄或驗(yàn)證那樣被完全重構(gòu)為自己的模塊。因此,使用AOP,您可以將這些內(nèi)容排除在主要代碼之外,并按如下方式垂直定義:
function mainProgram()
{
var x = foo();
doSomethingWith(x);
return x;
}
aspect logging
{
before (mainProgram is called):
{
log.Write("entering mainProgram");
}
after (mainProgram is called):
{
log.Write( "exiting mainProgram with return value of "
+ mainProgram.returnValue);
}
}
aspect verification
{
before (doSomethingWith is called):
{
if (doSomethingWith.arguments[0] == null)
{
throw NullArgumentException();
}
if (!doSomethingWith.caller.isAuthenticated)
{
throw Securityexception();
}
}
}
然后使用aspect-weaver將代碼編譯為以下內(nèi)容:
function mainProgram()
{
log.Write("entering mainProgram");
var x = foo();
if (x == null) throw NullArgumentException();
if (!mainProgramIsAuthenticated()) throw Securityexception();
doSomethingWith(x);
log.Write("exiting mainProgram with return value of "+ x);
return x;
}

TA貢獻(xiàn)1797條經(jīng)驗(yàn) 獲得超4個(gè)贊
為了完整性而從副本中復(fù)制(愛(ài)因斯坦):
經(jīng)典示例是安全性和日志記錄。與其在您的應(yīng)用程序內(nèi)編寫(xiě)代碼以記錄x的出現(xiàn)或檢查對(duì)象z的安全訪問(wèn)控制,不如使用普通代碼的“帶外”語(yǔ)言措辭,它可以系統(tǒng)地注入安全性或登錄沒(méi)有天真地將其包含在其中的例程這樣一種方式,即使您的代碼不提供它,它也會(huì)得到照顧。
一個(gè)更具體的示例是操作系統(tǒng)提供對(duì)文件的訪問(wèn)控制。一個(gè)軟件程序不需要檢查訪問(wèn)限制,因?yàn)榈讓酉到y(tǒng)可以完成該工作。
如果您認(rèn)為根據(jù)我的經(jīng)驗(yàn)需要AOP,則實(shí)際上確實(shí)需要投入更多的時(shí)間和精力來(lái)進(jìn)行系統(tǒng)內(nèi)適當(dāng)?shù)脑獢?shù)據(jù)管理,并著重考慮周全的結(jié)構(gòu)/系統(tǒng)設(shè)計(jì)。
- 3 回答
- 0 關(guān)注
- 516 瀏覽
添加回答
舉報(bào)