网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!
Go语言实现
type IFlyWeight interface {
Run()
}
type FlyWeight struct {
key string
}
func (f FlyWeight) Run() {
fmt.Println(f.key)
}
type FactoryFlyWeight struct {
flyWeight map[string]FlyWeight
}
func NewFactoryFlyWeight() *FactoryFlyWeight {
return &FactoryFlyWeight{flyWeight: make(map[string]FlyWeight)}
}
func (f *FactoryFlyWeight) GetFlyWeight(key string) (fly FlyWeight) {
var ok bool
if fly, ok = f.flyWeight[key]; !ok {
fly = FlyWeight{key: key}
f.flyWeight[key] = fly
}
return fly
}
func (f *FactoryFlyWeight) Count() int {
return len(f.flyWeight)
}
func main() {
a := NewFactoryFlyWeight()
a.GetFlyWeight("A").Run()
a.GetFlyWeight("A").Run()
a.GetFlyWeight("B").Run()
fmt.Println(a.Count())
}
享元模式优点
- 减少对象的创建,提高效率
- 缩小内存中对象的数量
享元模式缺点
- 使系统更加复杂,需要分离出内部状态和外部状态,使得程序的逻辑更加复杂
- 享元对象状态外部化,使运行时间变长
代理模式
为其他对象提供一种代理以控制对这个对象的访问
适用场景
- 监控、统计、鉴权、限流等
Go语言实现
type IExecutor interface {
RunFunc()
}
type SyncExecutor struct {
}
func (e SyncExecutor) RunFunc() {
time.Sleep(time.Second)
}
type ExecutorProxy struct {
executor IExecutor
}
func NewExecutorProxy(e IExecutor) *ExecutorProxy {
return &ExecutorProxy{executor: e}
}
func (e *ExecutorProxy) RunFunc() {
start := time.Now()
e.executor.RunFunc()
fmt.Printf("运行用时: %+v", time.Since(start))
}
func main() {
a := NewExecutorProxy(proxy.SyncExecutor{})
a.RunFunc()
}
代理模式优点
- 在客户端和目标对象间起到一个中介作用,保护目标对象
- 可以扩展目标对象的功能
- 将客户端和目标对象分离,降低了系统耦合度,增加了程序的可扩展性
代理模式缺点
- 使系统设计中类的数量增多,增加了系统的复杂度
- 在客户端和目标对象间增加一个代理对象,请求速度变慢
网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!
这里获取](https://bbs.csdn.net/topics/618658159)**
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!