背景
- 在原程序上加壳,ex. 壳=虚拟/保护/远程/日志记录 等
示例
using static System.Console;
namespace DesignPattern_Proxy
{
// 真实类接口,可与代理类互换
public interface ILogin
{
void Perform(string name);
}
// 真实类
public class RealLogin : ILogin
{
public void Perform(string name)
=> WriteLine($"{name} is logged in.");
}
// 代理类
public class LoginProxy : ILogin
{
private readonly ILogin login;
private readonly string password;
// 传入真实类
public LoginProxy(ILogin login, string password)
{
this.login = login;
this.password = password;
}
public void Perform(string name)
{
// 加壳
if (!IsRightPassword(password))
{
WriteLine($"Invalid password of {name}!");
return;
}
login.Perform(name);
}
private bool IsRightPassword(string password)
=> password == "123456";
}
class Program
{
static void Main(string[] args)
{
var real = new RealLogin();
var proxy = new LoginProxy(real, "012345");
proxy.Perform("Zhang San");
proxy = new LoginProxy(real, "123456");
proxy.Perform("Zhang San");
ReadKey();
}
}
}
网友评论