Skip to content

Commit d140f90

Browse files
committed
Proxy: improve conceptual example
1 parent 404189c commit d140f90

File tree

1 file changed

+90
-45
lines changed

1 file changed

+90
-45
lines changed

Proxy.Conceptual/Program.cs

Lines changed: 90 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -1,76 +1,121 @@
1-
using System;
1+
 // EN: Proxy Design Pattern
2+
//
3+
// Intent: Provide a surrogate or placeholder for another object to control
4+
// access to the original object or to add other responsibilities.
5+
//
6+
// RU: Паттерн Заместитель
7+
//
8+
// Назначение: Предоставляет заменитель или местозаполнитель для другого
9+
// объекта, чтобы контролировать доступ к оригинальному объекту или добавлять
10+
// другие обязанности.
11+
12+
using System;
213

314
namespace RefactoringGuru.DesignPatterns.Proxy.Conceptual
415
{
5-
class Program
6-
{
7-
static void Main(string[] args)
8-
{
9-
Client client = new Client();
10-
Console.WriteLine("Client: Executing the client code with a real subject:");
11-
12-
RealSubject realSubject = new RealSubject();
13-
14-
client.ClientCode(realSubject);
15-
16-
Console.WriteLine();
17-
18-
Console.WriteLine("Client: Executing the same client code with a proxy:");
19-
20-
Proxy proxy = new Proxy();
21-
22-
client.ClientCode(proxy);
23-
}
24-
}
25-
26-
public class Client
27-
{
28-
public void ClientCode(Subject subject)
29-
{
30-
subject.Request();
31-
}
32-
}
33-
34-
public abstract class Subject
16+
// EN: The Subject interface declares common operations for both RealSubject and
17+
// the Proxy. As long as the client works with RealSubject using this interface,
18+
// you'll be able to pass it a proxy instead of a real subject.
19+
//
20+
// RU: Интерфейс Субъекта объявляет общие операции как для Реального Субъекта,
21+
// так и для Заместителя. Пока клиент работает с Реальным Субъектом, используя
22+
// этот интерфейс, вы сможете передать ему заместителя вместо реального
23+
// субъекта.
24+
public interface Subject
3525
{
36-
public abstract void Request();
26+
void Request();
3727
}
38-
28+
29+
// EN: The RealSubject contains some core business logic. Usually, RealSubjects
30+
// are capable of doing some useful work which may also be very slow or
31+
// sensitive - e.g. correcting input data. A Proxy can solve these issues
32+
// without any changes to the RealSubject's code.
33+
//
34+
// RU: Реальный Субъект содержит некоторую базовую бизнес-логику. Как правило,
35+
// Реальные Субъекты способны выполнять некоторую полезную работу, которая к
36+
// тому же может быть очень медленной или точной – например, коррекция входных
37+
// данных. Заместитель может решить эти задачи без каких-либо изменений в коде
38+
// Реального Субъекта.
3939
class RealSubject : Subject
4040
{
41-
public override void Request()
41+
public void Request()
4242
{
4343
Console.WriteLine("RealSubject: Handling Request.");
4444
}
4545
}
46-
46+
47+
// EN: The Proxy has an interface identical to the RealSubject.
48+
//
49+
// RU: Интерфейс Заместителя идентичен интерфейсу Реального Субъекта.
4750
class Proxy : Subject
4851
{
49-
RealSubject realSubject;
52+
private RealSubject _realSubject;
53+
54+
public Proxy(RealSubject realSubject)
55+
{
56+
this._realSubject = realSubject;
57+
}
5058

51-
public override void Request()
59+
// EN: The most common applications of the Proxy pattern are lazy loading,
60+
// caching, controlling the access, logging, etc. A Proxy can perform one of
61+
// these things and then, depending on the result, pass the execution to the
62+
// same method in a linked RealSubject object.
63+
//
64+
// RU: Наиболее распространёнными областями применения паттерна Заместитель
65+
// являются ленивая загрузка, кэширование, контроль доступа, ведение журнала
66+
// и т.д. Заместитель может выполнить одну из этих задач, а затем, в
67+
// зависимости от результата, передать выполнение одноимённому методу в
68+
// связанном объекте класса Реального Субъект.
69+
public void Request()
5270
{
53-
if (this.checkAccess())
71+
if (this.CheckAccess())
5472
{
55-
realSubject = new RealSubject();
56-
realSubject.Request();
73+
this._realSubject = new RealSubject();
74+
this._realSubject.Request();
5775

58-
this.logAccess();
76+
this.LogAccess();
5977
}
60-
6178
}
6279

63-
public bool checkAccess()
80+
public bool CheckAccess()
6481
{
82+
// EN: Some real checks should go here.
83+
//
84+
// RU: Некоторые реальные проверки должны проходить здесь.
6585
Console.WriteLine("Proxy: Checking access prior to firing a real request.");
6686

6787
return true;
6888
}
6989

70-
public void logAccess()
90+
public void LogAccess()
7191
{
7292
Console.WriteLine("Proxy: Logging the time of request.");
7393
}
7494
}
75-
}
95+
96+
public class Client
97+
{
98+
public void ClientCode(Subject subject)
99+
{
100+
subject.Request();
101+
}
102+
}
103+
104+
class Program
105+
{
106+
static void Main(string[] args)
107+
{
108+
Client client = new Client();
109+
110+
Console.WriteLine("Client: Executing the client code with a real subject:");
111+
RealSubject realSubject = new RealSubject();
112+
client.ClientCode(realSubject);
76113

114+
Console.WriteLine();
115+
116+
Console.WriteLine("Client: Executing the same client code with a proxy:");
117+
Proxy proxy = new Proxy(realSubject);
118+
client.ClientCode(proxy);
119+
}
120+
}
121+
}

0 commit comments

Comments
 (0)