结构 |
|
意图 | 为其他对象提供一种代理以控制对这个对象的访问。 |
适用性 |
|
1 using System; 2 using System.Threading; 3 4 /// <summary> 5 /// Summary description for Client. 6 /// </summary> 7 abstract class CommonSubject 8 { 9 abstract public void Request(); 10 } 11 12 class ActualSubject : CommonSubject 13 { 14 public ActualSubject() 15 { 16 // Assume constructor here does some operation that takes quite a 17 // while - hence the need for a proxy - to delay incurring this 18 // delay until (and if) the actual subject is needed 19 Console.WriteLine("Starting to construct ActualSubject"); 20 Thread.Sleep(1000); // represents lots of processing! 21 Console.WriteLine("Finished constructing ActualSubject"); 22 } 23 24 override public void Request() 25 { 26 Console.WriteLine("Executing request in ActualSubject"); 27 } 28 } 29 30 class Proxy : CommonSubject 31 { 32 ActualSubject actualSubject; 33 34 override public void Request() 35 { 36 if (actualSubject == null) 37 actualSubject = new ActualSubject(); 38 actualSubject.Request(); 39 } 40 41 } 42 43 public class Client 44 { 45 public static int Main(string[] args) 46 { 47 Proxy p = new Proxy(); 48 49 // Perform actions here 50 // . . . 51 52 if (1==1) // at some later point, based on a condition, 53 p.Request();// we determine if we need to use subject 54 55 return 0; 56 } 57 }
代理模式
时间: 2024-10-25 20:40:26