空对象与观察者模式的深入解析
在软件开发中,处理空引用和实现组件间的通知机制是常见的需求。本文将深入探讨空对象模式的不同实现方式,以及观察者模式在 C# 中的应用。
空对象模式
空对象模式主要用于处理可能出现的空引用情况,避免在代码中频繁进行空检查。下面将介绍几种不同的实现方式。
可空虚拟代理
这种方式只需对 BankAccount
类进行一处修改,是侵入性最小的方法。它通过构建一个虚拟代理来处理日志记录器,允许底层的日志记录器为 null
。
class OptionalLog : ILog
{
private ILog impl;
public OptionalLog(ILog impl) { this.impl = impl; }
public void Info(string msg) { impl?.Info(msg); }
public void Warn(string msg) { impl?.Warn(msg); }
}
private const ILog NoLogging = null;
public BankAccount([CanBeNull] ILog log = NoLogging)
{
this.log = new OptionalLog(log);
}
该方法的优点是侵入性小,允许原本不允许为 null
的地方传入 null
,同时通过默认值的名