public class CompositeFlyweight : IFlyweight
{
private List<IFlyweight> _children = new();
public void Add(IFlyweight flyweight) => _children.Add(flyweight);
public void Operation(string extrinsicState)
{
foreach (var child in _children)
child.Operation(extrinsicState);
}
}
(3)扩展:内存池技术
在 C# 中,可通过 ObjectPool 或自定义池实现高效对象复用:
csharp复制代码
public class ObjectPool<T> where T : new()
{
private readonly ConcurrentBag<T> _objects = new();
public T GetObject() => _objects.TryTake(out T item) ? item : new T();
public void ReturnObject(T item) => _objects.Add(item);
}
// 抽象接口:送礼行为
public interface IGiveGift {
void GiveFlowers();
void GiveChocolate();
}
// 真实对象:追求者
public class Pursuit : IGiveGift {
private SchoolGirl girl;
public Pursuit(SchoolGirl girl) => this.girl = girl;
public void GiveFlowers() => Console.WriteLine($"送花给{girl.Name}");
public void GiveChocolate() => Console.WriteLine($"送巧克力给{girl.Name}");
}
// 代理对象:媒婆
public class Proxy : IGiveGift {
private Pursuit pursuit;
public Proxy(SchoolGirl girl) => pursuit = new Pursuit(girl);
public void GiveFlowers() {
Console.WriteLine("[媒婆日志] 开始送花");
pursuit.GiveFlowers();
}
public void GiveChocolate() {
Console.WriteLine("[媒婆日志] 开始送巧克力");
pursuit.GiveChocolate();
}
}
// 客户端调用
SchoolGirl jiaojiao = new SchoolGirl { Name = "李娇娇" };
IGiveGift proxy = new Proxy(jiaojiao);
proxy.GiveFlowers();
(2)虚拟代理(延迟加载)
实现要点
延迟创建高开销对象,仅在首次访问时初始化真实对象。
适用于大文件加载、数据库连接等场景。
代码示例(图片加载代理)
csharp复制代码
public interface IImage {
void Display();
}
public class RealImage : IImage {
private string _path;
public RealImage(string path) {
_path = path;
LoadFromDisk(); // 高开销操作
}
public void Display() => Console.WriteLine($"显示图片:{_path}");
private void LoadFromDisk() => Console.WriteLine($"加载图片:{_path}");
}
public class ProxyImage : IImage {
private string _path;
private RealImage _realImage;
public ProxyImage(string path) => _path = path;
public void Display() {
if (_realImage == null) {
_realImage = new RealImage(_path); // 延迟初始化
}
_realImage.Display();
}
}
// 客户端调用
IImage image = new ProxyImage("large_image.jpg");
image.Display(); // 第一次调用时才加载图片
(3)保护代理(权限控制)
实现要点
验证访问权限,限制非法操作。
典型场景:敏感数据访问、API权限校验。
代码示例
csharp复制代码
public interface ISensitiveData {
void AccessData();
}
public class SensitiveData : ISensitiveData {
public void AccessData() => Console.WriteLine("访问敏感数据");
}
public class ProtectionProxy : ISensitiveData {
private SensitiveData _data;
private string _userRole;
public ProtectionProxy(string role) => _userRole = role;
public void AccessData() {
if (_userRole == "Admin") {
if (_data == null) _data = new SensitiveData();
_data.AccessData();
} else {
Console.WriteLine("权限不足!");
}
}
}
// 客户端调用
ISensitiveData proxy = new ProtectionProxy("User");
proxy.AccessData(); // 输出:"权限不足!"
(4)动态代理(运行时生成)
实现要点
通过反射或第三方库(如Castle DynamicProxy)自动生成代理类。
避免静态代理的代码冗余,适用于AOP编程。
示例(使用Castle.Core)
csharp复制代码
// 定义拦截器
public class LogInterceptor : IInterceptor {
public void Intercept(IInvocation invocation) {
Console.WriteLine($"[日志] 调用方法:{invocation.Method.Name}");
invocation.Proceed();
}
}
// 生成动态代理
var proxyGenerator = new ProxyGenerator();
var service = proxyGenerator.CreateInterfaceProxyWithTarget<IService>(
new ServiceImpl(),
new LogInterceptor()
);
service.Execute(); // 输出日志并执行真实方法