1
using System;
2
using System.Collections.Generic;
3
using System.Text;
4
5
namespace ProxyDemo
6
{
7
class SubjectAccessor
8
{
9
public interface ISubject
10
{
11
string Request();
12
}
13
14
private class Subject
15
{
16
public string Request()
17
{
18
return "Subject Request " + "Choose left door\n";
19
}
20
}
21
22
public class Proxy : ISubject
23
{
24
Subject subject;
25
26
public string Request()
27
{
28
// 虚拟代理仅在方法被第一次调用时创建对象
29
if (subject == null)
30
{
31
Console.WriteLine("Subject inactive");
32
subject = new Subject();
33
}
34
35
Console.WriteLine("Subject active");
36
return "Proxy: Call to " + subject.Request();
37
}
38
}
39
40
public class ProtectionProxy : ISubject
41
{
42
// 认证代理首先要求一个密码
43
Subject subject;
44
string password = "abc";
45
46
public string Authenticate(string supplied)
47
{
48
if (supplied != password)
49
return "Protection Proxy: NO access";
50
else
51
subject = new Subject();
52
return "Protetion Proxy: Authenticated";
53
}
54
55
public string Request()
56
{
57
if (subject == null)
58
return "Proctection Proxy: Authentictate first";
59
else
60
return "Proctection Proxy: Call to " + subject.Request();
61
}
62
}
63
}
64
}
65
using System;
using System.Collections.Generic;
using System.Text;
namespace ProxyDemo
{
class Client : SubjectAccessor
{
static void Main(string[] args)
{
Console.WriteLine("Proxy Pattery\n");
ISubject subject = new Proxy();
Console.WriteLine(subject.Request());
Console.WriteLine(subject.Request());
ISubject protectionproxy = new ProtectionProxy();
Console.WriteLine(protectionproxy.Request());
Console.WriteLine((protectionproxy as ProtectionProxy).Authenticate("Secret"));
Console.WriteLine((protectionproxy as ProtectionProxy).Authenticate("abc"));
Console.WriteLine(protectionproxy.Request());
Console.ReadLine();
}
}
}
西安大德信息技术有限公司品牌形象塑造专家,致力提供高端品牌软件开发,高端网站建设,以及各种软件免费咨询等服务;我们能让企业品牌更有力量,咨询热线:029-88662010