利用Scala特征(trait)的堆叠操作特性进行切面编程
生活随笔
收集整理的這篇文章主要介紹了
利用Scala特征(trait)的堆叠操作特性进行切面编程
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
2019獨角獸企業重金招聘Python工程師標準>>>
????? ? 在Java中進行切面編程,通常需要借助Spring或AspectJ等第三方類庫,而在scala中,通過巧妙的使用特征(trait)可以實現部分AOP的效果。比如我有這樣一個操作:
trait Service{def doAction(): Unit }我希望在doAction的之前和之后做一些額外的操作(比如記錄日志,權限控制等),下面我定義了liang trait BeforeServiceAspect extends Service{abstract override def doAction(): Unit = {println("before doAction ... " )super.doAction();} }trait AfterServiceAspect extends Service{abstract override def doAction(): Unit = {super.doAction();println("after doAction ... "); } }class ServiceImpl extends Service{override def doAction(){println("do job");} }
? ? 然后我們可以這樣 實例化:
val s = new ServiceImpl with BeforeServiceAspect with AfterServiceAspect? ?你會發現當執行s.doAction的時候會打印出: before doAction ...
do job
after doAction ...
這就是利用了trait的堆疊特性。
?
轉載于:https://my.oschina.net/aiguozhe/blog/35250
總結
以上是生活随笔為你收集整理的利用Scala特征(trait)的堆叠操作特性进行切面编程的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Office Communication
- 下一篇: iOS开发笔记[16/50]:Views