package factory_cache
import "errors"
type Cache interface { // 定义一个Cache,作为父类
Set(key, value string)
Get(key string) string
}
type RedisCache struct { // 实现具体的Cache:RedisCache
data map[string]string
}
func (redis *RedisCache) Set(key, value string) {
redis.data[key] = value
}
func (redis *RedisCache) Get(key string) string {
return "redis: " + redis.data[key]
}
type MemCache struct { // 实现具体的Cache:Memcache
data map[string]string
}
func (mem *MemCache) Set(key, value string) {
mem.data[key] = value
}
func (mem *MemCache) Get(key string) string {
return "mem: " + mem.data[key]
}
type cacheType int
const (
redis cacheType = iota
mem
)
type CacheFactory struct { // 实现Cache的工厂
}
func (factory *CacheFactory) Create(cacheType cacheType) (Cache, error) {
if cacheType == redis {
return &RedisCache{
data: map[string]string{},
}, nil
}
if cacheType == mem {
return &MemCache{
data: map[string]string{},
}, nil
}
return nil, errors.New("error cache type")
}