type DataStore interface { Get(key string) (string, error) Set(key, value string) error }
type SimpleStore struct { data map[string]string }
func (s *SimpleStore) Get(key string) (string, error) { if value, exists := s.data[key]; exists { return value, nil } return "", fmt.Errorf("key not found: %s", key) }
func (s *SimpleStore) Set(key, value string) error { if s.data == nil { s.data = make(map[string]string) } s.data[key] = value return nil }
type LoggingStore struct { store DataStore }
func (l *LoggingStore) Get(key string) (string, error) { fmt.Printf("Getting key: %s\n", key) value, err := l.store.Get(key) if err != nil { fmt.Printf("Error getting key %s: %v\n", key, err) } else { fmt.Printf("Got value: %s\n", value) } return value, err }
func (l *LoggingStore) Set(key, value string) error { fmt.Printf("Setting key: %s, value: %s\n", key, value) return l.store.Set(key, value) }
type CachingStore struct { store DataStore cache map[string]string mutex sync.RWMutex }
func (c *CachingStore) Get(key string) (string, error) { c.mutex.RLock() if value, exists := c.cache[key]; exists { c.mutex.RUnlock() fmt.Printf("Cache hit for key: %s\n", key) return value, nil } c.mutex.RUnlock() value, err := c.store.Get(key) if err == nil { c.mutex.Lock() if c.cache == nil { c.cache = make(map[string]string) } c.cache[key] = value c.mutex.Unlock() } return value, err }
func (c *CachingStore) Set(key, value string) error { err := c.store.Set(key, value) if err == nil { c.mutex.Lock() if c.cache == nil { c.cache = make(map[string]string) } c.cache[key] = value c.mutex.Unlock() } return err }
|