Created
October 18, 2018 07:19
-
-
Save XUJiahua/730ace54c904b7887563bfb8d92bbd55 to your computer and use it in GitHub Desktop.
proxy = embedding + interface
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 embintf | |
import ( | |
"github.com/sirupsen/logrus" | |
"time" | |
) | |
type Cat struct { | |
ID int64 | |
} | |
type CatRepo interface { | |
Get(id int64) (*Cat, error) | |
Set(cat *Cat) error | |
} | |
// db impl | |
type dbCatRepo struct{} | |
// inject dependencies | |
func NewDBCatRepo(conn string) *dbCatRepo { | |
return &dbCatRepo{} | |
} | |
func (dbCatRepo) Get(id int64) (*Cat, error) { | |
logrus.Debug("reading from DB") | |
time.Sleep(time.Microsecond * 200) | |
return &Cat{id}, nil | |
} | |
func (dbCatRepo) Set(cat *Cat) error { | |
logrus.Debug("writing to DB") | |
time.Sleep(time.Second) | |
return nil | |
} | |
// proxy by embedding + interface | |
// cache proxy impl | |
type cachedCatRepo struct { | |
*dbCatRepo | |
cache map[int64]*Cat | |
} | |
// inject dependencies | |
func NewCachedCatRepo(mCatRepo *dbCatRepo) *cachedCatRepo { | |
return &cachedCatRepo{ | |
dbCatRepo: mCatRepo, | |
cache: make(map[int64]*Cat), | |
} | |
} | |
// overwrite | |
func (r cachedCatRepo) Get(id int64) (*Cat, error) { | |
logrus.Debug("reading from cache") | |
if cat, ok := r.cache[id]; ok { | |
return cat, nil | |
} | |
cat, err := r.dbCatRepo.Get(id) | |
if err != nil { | |
return nil, err | |
} | |
logrus.Debug("writing to cache") | |
r.cache[id] = cat | |
return cat, nil | |
} |
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 embintf | |
import "testing" | |
func BenchmarkCachedCatRepo_Get(b *testing.B) { | |
mCatRepo := NewDBCatRepo("127.0.0.1:3306") | |
rCatRepo := NewCachedCatRepo(mCatRepo) | |
for i := 0; i < b.N; i++ { | |
rCatRepo.Get(1) | |
} | |
} | |
func BenchmarkDbCatRepo_Get(b *testing.B) { | |
mCatRepo := NewDBCatRepo("127.0.0.1:3306") | |
for i := 0; i < b.N; i++ { | |
mCatRepo.Get(1) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment