搜尋
首頁後端開發Golanggo語言不支援aop嗎

go語言不支援aop嗎

Dec 27, 2022 pm 05:04 PM
golanggo語言aop面向切面程式設計

go語言支援aop。 AOP是指面向切面編程,是透過預編譯方式和運行期間動態代理實現程序功能的統一維護的一種技術;AOP是面向對像中的一種方式,主要應用場景:日誌記錄,性能統計,安全控制,事務處理,異常處理等等。

go語言不支援aop嗎

本教學操作環境:windows7系統、GO 1.18版本、Dell G3電腦。

什麼是aop?

在軟體業,AOP為Aspect Oriented Programming的縮寫,意為:面向切面編程,透過預編譯方式和運行期間動態代理實現程序功能的統一維護的一種技術。 AOP是OOP的延續,是軟體開發中的熱點,也是Spring框架中的重要內容,是函數式程式設計的衍生範式。利用AOP可以對業務邏輯的各個部分進行隔離,從而使得業務邏輯各部分之間的耦合度降低,提高程序的可重用性,同時提高了開發的效率。

面向切面程式設計是物件導向中的一種方式而已。在程式碼執行過程中,動態嵌入其他程式碼,叫做面向切面程式設計。常見的使用場景:

  • 日誌

  • #事物

  • ##資料庫操作

面向切面編程,就是將交叉業務邏輯封裝成切面,利用AOP的功能將切面織入到主業務邏輯中。所謂交叉業務邏輯是指,通用的,與主業務邏輯無關的程式碼,如安全檢查,事物,日誌等。若不使用AOP,則會出現程式碼糾纏,即交叉業務邏輯與主業務邏輯混合在一起。這樣,會使業務邏輯變得混雜不清。

主要應用場景:日誌記錄,效能統計,安全控制,事務處理,異常處理等等。

核心概念

  • #JoinPoint:連接點。是程式執行中的一個精確執行點,例如類別中的一個方法。

  • PointCut:切入點。指定哪些組件的哪些方法使用切面組件。

  • Advice:通知,用於指定具體作用的位置,是方法之前或之後等等,分為前置通知,後置通知,異常通知,返回通知,環繞通知。

  • Aspect: 切面。封裝通用業務邏輯的元件,也就是我們想要插入的程式碼內容。

其內在設計模式為代理模式。

go語言支不支援aop?

go語言支援aop。

Go實作AOP的範例:

// User 
type User struct {
	Name string
	Pass string
}

// Auth 验证
func (u *User) Auth() {
	// 实际业务逻辑
	fmt.Printf("register user:%s, use pass:%s\n", u.Name, u.Pass)
}


// UserAdvice 
type UserAdvice interface {
    // Before 前置通知
    Before(user *User) error
    
    // After 后置通知
	After(user *User)
}

// ValidatePasswordAdvice 用户名验证
type ValidateNameAdvice struct {
}

// ValidatePasswordAdvice 密码验证
type ValidatePasswordAdvice struct {
	MinLength int
	MaxLength int
}

func (ValidateNameAdvice) Before(user *User) error {
	fmt.Println("ValidateNameAdvice before")
	if user.Name == "admin" {
		return errors.New("admin can't be used")
	}

	return nil
}

func (ValidateNameAdvice) After(user *User) {
	fmt.Println("ValidateNameAdvice after")
	fmt.Printf("username:%s validate sucess\n", user.Name)
}

// Before 前置校验
func (advice ValidatePasswordAdvice) Before(user *User) error {
	fmt.Println("ValidatePasswordAdvice before")
	if user.Pass == "123456" {
		return errors.New("pass isn't strong")
	}

	if len(user.Pass) > advice.MaxLength {
		return fmt.Errorf("len of pass must less than:%d", advice.MaxLength)
	}

	if len(user.Pass) < advice.MinLength {
		return fmt.Errorf("len of pass must greater than:%d", advice.MinLength)
	}

	return nil
}

func (ValidatePasswordAdvice) After(user *User) {
	fmt.Println("ValidatePasswordAdvice after")
	fmt.Printf("password:%s validate sucess\n", user.Pass)
}

// UserAdviceGroup,通知管理组
type UserAdviceGroup struct {
	items []UserAdvice
}

// Add 注入可选通知
func (g *UserAdviceGroup) Add(advice UserAdvice) {
	g.items = append(g.items, advice)
}

func (g *UserAdviceGroup) Before(user *User) error {
	for _, item := range g.items {
		if err := item.Before(user); err != nil {
			return err
		}
	}

	return nil
}

// After
func (g *UserAdviceGroup) After(user *User) {
	for _, item := range g.items {
		item.After(user)
	}
}

// UserProxy 代理,也是切面
type UserProxy struct {
	user *User
}

// NewUser return UserProxy
func NewUser(name, pass string) UserProxy {
	return UserProxy{user:&User{Name:name, Pass:pass}}
}

// Auth 校验,切入点
func (p UserProxy) Auth() {
	group := UserAdviceGroup{}
	group.Add(&ValidatePasswordAdvice{MaxLength:10, MinLength:6})
    group.Add(&ValidateNameAdvice{})
    
    // 前置通知
	if err := group.Before(p.user); err != nil {
		panic(err)
	}

    // 实际逻辑
	p.user.Auth()

    // 后置通知
	group.After(p.user)

}

使用AOP模式進行解耦,分離主業務與副業務。其實就那樣。

【相關推薦:

Go影片教學程式設計教學

以上是go語言不支援aop嗎的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
在GO中使用init進行包裝初始化在GO中使用init進行包裝初始化Apr 24, 2025 pm 06:25 PM

在Go中,init函數用於包初始化。 1)init函數在包初始化時自動調用,適用於初始化全局變量、設置連接和加載配置文件。 2)可以有多個init函數,按文件順序執行。 3)使用時需考慮執行順序、測試難度和性能影響。 4)建議減少副作用、使用依賴注入和延遲初始化以優化init函數的使用。

GO的選擇語句:多路復用並發操作GO的選擇語句:多路復用並發操作Apr 24, 2025 pm 05:21 PM

go'SselectStatementTreamLinesConcurrentProgrambyMultiplexingOperations.1)itallowSwaitingOnMultipleChannEloperations,執行thefirstreadyone.2)theDefirstreadyone.2)thedefefcasepreventlocksbysbysbysbysbysbythoplocktrograpraproxrograpraprocrecrecectefnoopeready.3)

GO中的高級並發技術:上下文和候補組GO中的高級並發技術:上下文和候補組Apr 24, 2025 pm 05:09 PM

contextancandwaitgroupsarecrucialingoformanaginggoroutineseflect.1)context contextsallowsAllowsAllowsAllowsAllowsAllingCancellationAndDeadLinesAcrossapibiboundaries,確保GoroutinesCanbestoppedGrace.2)WaitGroupsSynChronizeGoroutines,確保Allimizegoroutines,確保AllizeNizeGoROutines,確保AllimizeGoroutines

使用微服務體系結構的好處使用微服務體系結構的好處Apr 24, 2025 pm 04:29 PM

goisbeneformervicesduetoitssimplicity,效率,androbustConcurrencySupport.1)go'sdesignemphasemphasizessimplicity and效率,Idealformicroservices.2))其ConcconcurnCurnInesSandChannelsOdinesSallessallessallessAlloSalosalOsalOsalOsalOndlingConconcConccompi.3)

Golang vs. Python:利弊Golang vs. Python:利弊Apr 21, 2025 am 12:17 AM

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

Golang和C:並發與原始速度Golang和C:並發與原始速度Apr 21, 2025 am 12:16 AM

Golang在並發性上優於C ,而C 在原始速度上優於Golang。 1)Golang通過goroutine和channel實現高效並發,適合處理大量並發任務。 2)C 通過編譯器優化和標準庫,提供接近硬件的高性能,適合需要極致優化的應用。

為什麼要使用Golang?解釋的好處和優勢為什麼要使用Golang?解釋的好處和優勢Apr 21, 2025 am 12:15 AM

選擇Golang的原因包括:1)高並發性能,2)靜態類型系統,3)垃圾回收機制,4)豐富的標準庫和生態系統,這些特性使其成為開發高效、可靠軟件的理想選擇。

Golang vs.C:性能和速度比較Golang vs.C:性能和速度比較Apr 21, 2025 am 12:13 AM

Golang適合快速開發和並發場景,C 適用於需要極致性能和低級控制的場景。 1)Golang通過垃圾回收和並發機制提升性能,適合高並發Web服務開發。 2)C 通過手動內存管理和編譯器優化達到極致性能,適用於嵌入式系統開發。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能