直接与间接
人们对于复杂软件系统常常有一种处理手法,即增加一层间接层,从而对系统获得一种更灵活、满足特定需求的解决方案。
代理模式
动机
意图
结构
代码
Version1
//version1
//由于集中控制需求,放在集中公司总部机器上
class Employee
{
public void GetSalary()
{
}
public void Report()
{
}
public void ApplyVacation()
{
}
}
//可能应用于各个地区机器上
class HrSystem
{
public void Process()
{
//此时这样不可用,这样使用原则是Employee类一定与HrSystem在同一地址空间
Employee employee = new Employee();
employee.Report();
//...
employee.ApplyVacation();
//...
}
}
解决
Version2
//version2
//由于集中控制需求,放在集中公司总部机器上
interface IEmployee
{
void GetSalary();
void Report();
void ApplyVacation();
}
//运行在Internet远端一台机器上
class Employee:IEmployee
{
public void GetSalary()
{
}
public void Report()
{
}
public void ApplyVacation()
{
}
}
//EmployeeProxy和HrSystem是运行在同一个地址空间
//运行在本地Windows Form
class EmployeeProxy : IEmployee
{
public EmployeeProxy()//构造器
{
//对对象创建的一种SOAP封装
}
public void GetSalary()
{
//对访问对象的一种SOPA封装
//发送SOAP数据,到远程机器上。(监听来调用Employee)
//如果有返回值,接收返回值SOAP,解包,返回原生(RAW)的C#数据
}
public void Report()
{
//...
}
public void ApplyVacation()
{
//...
}
}
//可能应用于各个地区机器上
class HrSystem
{
public void Process()
{
IEmployee employee = new EmployeeProxy();
employee.Report();
employee.ApplyVacation();
}
}
要点
C#不支持操作符重载,用接口使用代理
Copy-on-Write实现
1、大部分字符串实现方式
string s1 = "hello";
string s2 = "hello";
//ToUpper() 转化为大写字母
//s1.ToUpper();//不能改变S1
s1=s1.ToUpper();//这样才可以改变s1
2、Copy-on-Write实现
StringBuilder sb1 = new StringBuilder("hello");
StringBuilder sb2 = new StringBuilder("hello");
sb1.Replace("l", "b");//sb1改变,将sb1中l改为b
注:当只有一个StringBuilder时,不再拷贝,直接在原处修改。
当字符串不倾向修改,使用String Builder要比使用String更耗内存。