设计模式 代理模式(Proxy Pattern)

意图 

  代理模式的主要作用是为其他对象提供一种代理以控制对这个对象的访问。在某些情况下,一个对象不想或者不能直接引用另一个对象,而代理对象可以在客户端和目标对象之间起到中介的作用。代理模式的思想是为了提供额外的处理或者不同的操作而在实际对象与调用者之间插入一个代理对象。这些额外的操作通常需要与实际对象进行通信。

适用性

1.在需要用比较通用和复杂的对象指针代替简单的指针的时候,使用P r o x y 模式。下面是一 些可以使用P r o x y 模式常见情况:
  1) 远程代理(Remote Proxy )为一个对象在不同的地址空间提供局部代表。 NEXTSTEP[Add94] 使用N X P r o x y 类实现了这一目的。Coplien[Cop92] 称这种代理为“大使” (A m b a s s a d o r )。
  2 )虚代理(Virtual Proxy )根据需要创建开销很大的对象。在动机一节描述的I m a g e P r o x y 就是这样一种代理的例子。
  3) 保护代理(Protection Proxy )控制对原始对象的访问。保护代理用于对象应该有不同 的访问权限的时候。例如,在C h o i c e s 操作系统[ C I R M 9 3 ]中K e m e l P r o x i e s 为操作系统对象提供 了访问保护。

2.对指向实际对象的引用计数,这样当该对象没有引用时,可以自动释放它(也称为S m a r tP o i n t e r s[ E d e 9 2 ] )。当第一次引用一个持久对象时,将它装入内存。

3.在访问一个实际对象前,检查是否已经锁定了它,以确保其他对象不能改变它。    

结构图

Code

 1 // Factory Method
2
3 /* Notes:
4 * When there is a large CPU/memory expense attached to handling an object
5 * directly, it can be useful to use a lightweight proxy in front of it,
6 * which can take its place until the real object is needed.
7 */
8
9 namespace Proxy_DesignPattern
10 {
11 using System;
12 using System.Threading;
13
14 /// <summary>
15 /// Summary description for Client.
16 /// </summary>
17 abstract class CommonSubject
18 {
19 abstract public void Request();
20 }
21
22 class ActualSubject : CommonSubject
23 {
24 public ActualSubject()
25 {
26 // Assume constructor here does some operation that takes quite a
27 // while - hence the need for a proxy - to delay incurring this
28 // delay until (and if) the actual subject is needed
29 Console.WriteLine("Starting to construct ActualSubject");
30 Thread.Sleep(1000); // represents lots of processing!
31 Console.WriteLine("Finished constructing ActualSubject");
32 }
33
34 override public void Request()
35 {
36 Console.WriteLine("Executing request in ActualSubject");
37 }
38 }
39
40 class Proxy : CommonSubject
41 {
42 ActualSubject actualSubject;
43
44 override public void Request()
45 {
46 if (actualSubject == null)
47 actualSubject = new ActualSubject();
48 actualSubject.Request();
49 }
50
51 }
52
53 public class Client
54 {
55 public static int Main(string[] args)
56 {
57 Proxy p = new Proxy();
58
59 // Perform actions here
60 // . . .
61
62 if (1==1) // at some later point, based on a condition,
63 p.Request();// we determine if we need to use subject
64
65 return 0;
66 }
67 }
68 }



人生如棋、我愿为卒、行动虽缓、从未退过

原文地址:https://www.cnblogs.com/sunjinpeng/p/2435827.html