了解 C# 中的代理模式
Understanding Proxy Pattern in C#
假设我正尝试通过其他 class 访问 class 的方法,例如
class SuperClass
{
public interface ISubject
{
void Print();
}
private class Subject : ISubject
{
public void Print()
{
Console.WriteLine("this is a print");
}
}
public class Proxy {
ISubject subject;
public void CallOtherMethod() {
subject = new Subject();
subject.Print();
}
}
}
class Client: SuperClass
{
static void Main() {
Proxy proxy = new Proxy();
proxy.CallOtherMethod();
}
}
这叫代理吗Class?或者它是否需要有一个接口作为参考然后我们必须调用该方法?例如像这样
class SuperClass
{
public interface ISubject
{
void Print();
}
private class Subject : ISubject
{
public void Print()
{
Console.WriteLine("this is a print");
}
}
public class Proxy : ISubject
{
ISubject subject;
public void Print()
{
subject = new Subject();
subject.Print();
}
}
}
class Client : SuperClass
{
static void Main()
{
ISubject proxy = new Proxy();
proxy.Print();
}
}
通常,代理模式的目的是拦截。也就是说,捕获对某种类型的某些(或所有)方法的调用,并在实际调用之前/之后执行一些操作。为此,代理必须从目标类型继承。
例如:
public class Subject
{
public virtual void Print()
{
Console.WriteLine("this is a print");
}
}
public class SubjectProxy : Subject
{
public override void Print()
{
Console.Write("Before calling base.Print()");
base.Print();
Console.Write("After calling base.Print()");
}
}
现在,当您在代码中的某个时刻期待 Subject
时,您实际上可能会得到 SubjectProxy
并且仍然将其视为 Subject
:
public Subject GetSubject()
{
return new SubjectProxy();
}
Subject subject = GetSubject();
subject.Print(); // would use the proxied method
(这并不是说实现拦截的唯一方法是通过继承。我认为有使用组合/装饰变化来实现的代理风格)
假设我正尝试通过其他 class 访问 class 的方法,例如
class SuperClass
{
public interface ISubject
{
void Print();
}
private class Subject : ISubject
{
public void Print()
{
Console.WriteLine("this is a print");
}
}
public class Proxy {
ISubject subject;
public void CallOtherMethod() {
subject = new Subject();
subject.Print();
}
}
}
class Client: SuperClass
{
static void Main() {
Proxy proxy = new Proxy();
proxy.CallOtherMethod();
}
}
这叫代理吗Class?或者它是否需要有一个接口作为参考然后我们必须调用该方法?例如像这样
class SuperClass
{
public interface ISubject
{
void Print();
}
private class Subject : ISubject
{
public void Print()
{
Console.WriteLine("this is a print");
}
}
public class Proxy : ISubject
{
ISubject subject;
public void Print()
{
subject = new Subject();
subject.Print();
}
}
}
class Client : SuperClass
{
static void Main()
{
ISubject proxy = new Proxy();
proxy.Print();
}
}
通常,代理模式的目的是拦截。也就是说,捕获对某种类型的某些(或所有)方法的调用,并在实际调用之前/之后执行一些操作。为此,代理必须从目标类型继承。
例如:
public class Subject
{
public virtual void Print()
{
Console.WriteLine("this is a print");
}
}
public class SubjectProxy : Subject
{
public override void Print()
{
Console.Write("Before calling base.Print()");
base.Print();
Console.Write("After calling base.Print()");
}
}
现在,当您在代码中的某个时刻期待 Subject
时,您实际上可能会得到 SubjectProxy
并且仍然将其视为 Subject
:
public Subject GetSubject()
{
return new SubjectProxy();
}
Subject subject = GetSubject();
subject.Print(); // would use the proxied method
(这并不是说实现拦截的唯一方法是通过继承。我认为有使用组合/装饰变化来实现的代理风格)