代理模式(Proxy Pattern)
代理模式(Proxy Pattern)是一种结构型模式,为其他对象提供一种代理以控制对这个对象的访问。在某些情况下,一个对象不适合或者不能直接引用另一个对象,而代理对象可以在客户端和目标对象之间起到中介的作用。代理模式又叫委托模式,是为某个对象提供一个代理对象,并且由代理对象控制对原对象的访问。代理模式通俗来讲就是我们生活中常见的中介。
using System;
namespace ConsoleApplication
{
//一般每个接口或类都写在单独的.cs文件中
//本示例为了执行查看方便才写在一起
///
/// 接口
///
public interface IMath
{
double Add(double x, double y);
double Sub(double x, double y);
double Mul(double x, double y);
double Div(double x, double y);
}
///
/// 具体实现
///
public class Math : IMath
{
public double Add(double x, double y)
{
return x + y;
}
public double Sub(double x, double y)
{
return x - y;
}
public double Mul(double x, double y)
{
return x * y;
}
public double Div(double x, double y)
{
return x / y;
}
}
///
/// 代理类
///
public class MathProxy : IMath
{
private Math _math = new Math();
public double Add(double x, double y)
{
return _math.Add(x, y);
}
public double Sub(double x, double y)
{
return _math.Sub(x, y);
}
public double Mul(double x, double y)
{
return _math.Mul(x, y);
}
public double Div(double x, double y)
{
return _math.Div(x, y);
}
}
class Program
{
static void Main(string[] args)
{
MathProxy proxy = new MathProxy();
Console.WriteLine("3 + 2 = " + proxy.Add(3, 2));
Console.WriteLine("4 - 2 = " + proxy.Sub(4, 2));
Console.WriteLine("5 * 2 = " + proxy.Mul(5, 2));
Console.WriteLine("6 / 2 = " + proxy.Div(6, 2));
}
}
}