Skip to content

Commit d88a940

Browse files
committed
面向实现的代理模式
1 parent 4fe7ca0 commit d88a940

File tree

1 file changed

+70
-2
lines changed

1 file changed

+70
-2
lines changed

docs/book/25-Patterns.md

Lines changed: 70 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -149,11 +149,79 @@ Hello World!
149149

150150
![](images/designproxy.png)
151151

152+
<!-- Fronting for an Implementation -->
153+
## 面向实现
152154

155+
代理模式和桥接模式都提供了在代码中使用的代理类;完成工作的真正类隐藏在这个代理类的后面。当您在代理中调用一个方法时,它只是反过来调用实现类中的方法。这两种模式非常相似,所以代理模式只是桥接模式的一种特殊情况。人们倾向于将两者合并,称为代理模式,但是术语“代理”有一个长期的和专门的含义,这可能解释了这两种模式不同的原因。基本思想很简单:从基类派生代理,同时派生一个或多个提供实现的类:创建代理对象时,给它一个可以调用实际工作类的方法的实现。
156+
157+
158+
在结构上,代理模式和桥接模式的区别很简单:代理模式只有一个实现,而桥接模式有多个实现。在设计模式中被认为是不同的:代理模式用于控制对其实现的访问,而桥接模式允许您动态更改实现。但是,如果您扩展了“控制对实现的访问”的概念,那么这两者就可以完美地结合在一起
159+
160+
**代理模式**
161+
162+
如果我们按照上面的关系图实现,它看起来是这样的:
163+
164+
```Java
165+
// patterns/ProxyDemo.java
166+
// Simple demonstration of the Proxy pattern
167+
interface ProxyBase {
168+
void f();
169+
170+
void g();
171+
172+
void h();
173+
}
174+
175+
class Proxy implements ProxyBase {
176+
private ProxyBase implementation;
177+
178+
Proxy() {
179+
implementation = new Implementation();
180+
}
181+
// Pass method calls to the implementation:
182+
@Override
183+
public void f() { implementation.f(); }
184+
@Override
185+
public void g() { implementation.g(); }
186+
@Override
187+
public void h() { implementation.h(); }
188+
}
189+
190+
class Implementation implements ProxyBase {
191+
public void f() {
192+
System.out.println("Implementation.f()");
193+
}
194+
195+
public void g() {
196+
System.out.println("Implementation.g()");
197+
}
198+
199+
public void h() {
200+
System.out.println("Implementation.h()");
201+
}
202+
}
203+
204+
public class ProxyDemo {
205+
public static void main(String[] args) {
206+
Proxy p = new Proxy();
207+
p.f();
208+
p.g();
209+
p.h();
210+
}
211+
}
212+
/*
213+
Output:
214+
Implementation.f()
215+
Implementation.g()
216+
Implementation.h()
217+
*/
218+
```
219+
220+
具体实现不需要与代理对象具有相同的接口;只要代理对象以某种方式“代表具体实现的方法调用,那么基本思想就算实现了。然而,拥有一个公共接口是很方便的,因此具体实现必须实现代理对象调用的所有方法。
221+
222+
**状态模式**
153223

154224

155-
<!-- Fronting for an Implementation -->
156-
## 面向实施
157225

158226

159227
<!-- Factories: Encapsulating Object Creation -->

0 commit comments

Comments
 (0)