Created
January 27, 2023 09:34
-
-
Save arriqaaq/f8ff0de7bb82b916e98d99d124b6c9bf to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"sync" | |
) | |
type LegacyService struct { | |
} | |
func (l *LegacyService) ExpensiveOperation(arg string) string { | |
// some expensive operation | |
return "result" | |
} | |
type Service interface { | |
Do(arg string) string | |
} | |
type ServiceAdapter struct { | |
LegacyService | |
cache map[string]string | |
mutex sync.RWMutex | |
} | |
func NewServiceAdapter() *ServiceAdapter { | |
return &ServiceAdapter{ | |
cache: make(map[string]string), | |
} | |
} | |
func (s *ServiceAdapter) Do(arg string) string { | |
s.mutex.RLock() | |
res, ok := s.cache[arg] | |
s.mutex.RUnlock() | |
if ok { | |
return res | |
} | |
res = s.ExpensiveOperation(arg) | |
s.mutex.Lock() | |
s.cache[arg] = res | |
s.mutex.Unlock() | |
return res | |
} | |
func main() { | |
adapter := NewServiceAdapter() | |
fmt.Println(adapter.Do("arg")) | |
fmt.Println(adapter.Do("arg")) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment