DesignParrten Null Object
构造注入时接收空对象导致执行错误的处理方式:
基本情况:
interface ILog { void Info(string msg); void Wran(string msg); } class BankAccount { private readonly ILog log; private int balance; public BankAccount(ILog log) { this.log = log; } public void Deposit(int amount) { balance += amount; log.Info($"Deposit:{amount}"); } } class Program { static void Main(string[] args) { BankAccount ba = new BankAccount(null); ba.Deposit(100); } }
解决方法1:
interface ILog { void Info(string msg); void Wran(string msg); } class BankAccount { private readonly ILog log; private int balance; public BankAccount(ILog log) { this.log = log; } public void Deposit(int amount) { balance += amount; // log.Info($"Deposit:{amount}"); log?.Info($"Deposit:{amount}");//增加obj? 不为null则执行 } } class Program { static void Main(string[] args) { BankAccount ba = new BankAccount(null); ba.Deposit(100); } }
使用AutoFac通过依赖注入的方式如何处理:
interface ILog { void Info(string msg); void Wran(string msg); } class BankAccount { private readonly ILog log; private int balance; public BankAccount(ILog log) { this.log = log; } public void Deposit(int amount) { balance += amount; // log.Info($"Deposit:{amount}"); log?.Info($"Deposit:{amount}"); } } class Program { static void Main(string[] args) { var cb = new ContainerBuilder(); cb.RegisterType(); cb.Register(ctx => new BankAccount(null)); using (var c=cb.Build()) { var ba = c.Resolve (); ba.Deposit(100); } } }
解决方法2 增加一个Ilog的实现类,不做任何处理:
interface ILog { void Info(string msg); void Wran(string msg); } class BankAccount { private readonly ILog log; private int balance; public BankAccount(ILog log) { this.log = log; } public void Deposit(int amount) { balance += amount; // log.Info($"Deposit:{amount}"); log?.Info($"Deposit:{amount}"); } } class NullLog : ILog { public void Info(string msg) { // } public void Wran(string msg) { // } } class Program { static void Main(string[] args) { var cb = new ContainerBuilder(); cb.RegisterType(); cb.RegisterType ().As (); using (var c=cb.Build()) { var ba = c.Resolve (); ba.Deposit(100); } } }