装饰模式:给一个静态或动态对象添加行为;
代理模式:为其他对象提供一种代理以控制对这个对象的访问。
Decorator Pattern
装饰模式
Decorator structural pattern allows extending the function of an existing object dynamically without altering its internals.
装饰器结构模式允许动态地扩展现有对象的功能,而不改变内部结构。
Decorators provide a flexible method to extend functionality of objects.
装修扩展功能的对象提供了一个灵活的方法。
Implementation
LogDecorate decorates a function with the signature func(int) int that manipulates integers and adds input/output logging capabilities.
ogdecorate装饰功能与特征函数(int)int操纵整数和增加输入/输出日志记录功能。
1 | type Object func(int) int |
Usage1
2
3
4
5
6
7
8
9func Double(n int) int {
return n * 2
}
f := LogDecorate(Double)
f(5)
// Starting execution with the integer 5
// Execution is completed with the result 10
Rules of Thumb
Unlike Adapter pattern, the object to be decorated is obtained by injection.
Decorators should not alter the interface of an object.
规则
与适配器模式不同,要修饰的对象是通过注入获得的。
装修不应改变一个对象的接口。
Proxy Pattern 代理模式
The proxy pattern provides an object that controls access to another object, intercepting all calls.
代理模式提供了一个对象,它控制对另一个对象的访问,拦截所有调用。
Implementation
The proxy could interface to anything: a network connection, a large object in memory, a file, or some other resource that is expensive or impossible to duplicate.
代理可以连接到任何东西:网络连接、内存中的大对象、文件或其他昂贵或不可能复制的资源。
Short idea of implementation:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35// To use proxy and to object they must implement same methods
// 要使用代理和对象,它们必须实现相同的方法
type IObject interface {
ObjDo(action string)
}
// Object represents real objects which proxy will delegate data
// 对象表示代理将委托数据的真实对象。
type Object struct {
action string
}
// ObjDo implements IObject interface and handel's all logic
// 目的objdo实现界面和汉德尔的所有逻辑
func (obj *Object) ObjDo(action string) {
// Action behavior 动作行为
fmt.Printf("I can, %s", action)
}
// ProxyObject represents proxy object with intercepts actions
// proxyobject代表代理对象拦截行动
type ProxyObject struct {
object *Object
}
// ObjDo are implemented IObject and intercept action before send in real Object
// objdo实施目的和拦截行动之前送实物
func (p *ProxyObject) ObjDo(action string) {
if p.object == nil {
p.object = new(Object)
}
if action == "Run" {
p.object.ObjDo(action) // Prints: I can, Run
}
}
Usage
More complex usage of proxy as example: User creates “Terminal” authorizes and PROXY send execution command to real Terminal object See proxy/main.go or view in the Playground.
代理为用户创建更复杂的用法:“终端”的授权和代理发送执行命令到真正的终端对象看到操场上查看代理/ main.go或。