Skip to content

Instantly share code, notes, and snippets.

@arriqaaq
Created January 27, 2023 09:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arriqaaq/f8ff0de7bb82b916e98d99d124b6c9bf to your computer and use it in GitHub Desktop.
Save arriqaaq/f8ff0de7bb82b916e98d99d124b6c9bf to your computer and use it in GitHub Desktop.
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