这样会给系统添加新的相互依赖。并且随着时间和需求的推移,会有更多的APP需要用Monitor来监测,这个Monitor工具也会被越来越对的if...else撑爆炸,而且代码随着APP越多,越难维护。最终会导致Monitor走向灭亡(下线)。
介于这种情况,可以用Monitor这个模块来生成其它的程序,使得系统能够用在需要的APP上。OOD给我们提供了一种机制来实现这种“依赖倒置”。
代码实现3:
//------------------------------------------------------------------------------ // <copyright file="Dependency.cs" company="CNBlogs Corporation"> // Copyright (C) 2015-2016 All Rights Reserved 作 者: 请叫我头头哥 // </copyright> TestLibrary.ExtensionsClass { using System; public interface IApp { bool Start(); bool ExportLog(); } public class AppOne : IApp { public bool Start() { Console.WriteLine(); return true; } public bool ExportLog() { Console.WriteLine(); return true; } } public class AppTwo : IApp { public bool Start() { Console.WriteLine(); return true; } public bool ExportLog() { Console.WriteLine(); return true; } } public class Monitor { private IApp iapp; public Monitor(IApp iapp) { this.iapp = iapp; } public bool StartApp() { return iapp.Start(); } public bool ExportAppLog() { return iapp.ExportLog(); } } }
代码解析3:
现在Monitor依赖于IApp这个接口,而与具体实现的APP类没有关系,所以无论再怎么添加APP都不会影响到Monitor本身,只需要去添加一个实现IApp接口的APP类就可以了。
vC# 接口隔离原则
1.概念:
客户端不应该依赖它不需要的接口,类间的依赖关系应该建立在最小的接口上
2.含义:
接口隔离原则的核心定义,不出现臃肿的接口(Fat Interface),但是“小”是有限度的,首先就是不能违反单一职责原则。
3.模拟场景:
一个OA系统,外部只负责提交和撤回工作流,内部负责审核和驳回工作流。
4.代码演示:
//------------------------------------------------------------------------------ // <copyright file="Dependency.cs" company="CNBlogs Corporation"> // Copyright (C) 2015-2016 All Rights Reserved 作 者: 请叫我头头哥 // </copyright> TestLibrary.ExtensionsClass { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public interface IReview { void ReviewWorkFlow(); void RejectWorkFlow(); } public class Review : IReview { public void ReviewWorkFlow() { Console.WriteLine(); } public void RejectWorkFlow() { Console.WriteLine(); } } public interface ISubmit { void SubmitWorkFlow(); void CancelWorkFlow(); } public class Submit : ISubmit { public void SubmitWorkFlow() { Console.WriteLine(); } public void CancelWorkFlow() { Console.WriteLine(); } } }
5.代码解析: