接口隔离原则(Interface Segregation Principle)ISP
2016-05-17 23:18
323 查看
using System; using System.Collections.Generic; using System.Text; namespace InterfaceSegregationPrinciple { //接口隔离原则(Interface Segregation Principle)ISP //Clients should not be forced to depend upon interfaces that they don's use.(客户端不应该依赖它不需要的接口) //The dependency of one class to another one should depend on the smallest possible interface.(类间的依赖关系应该建立在最小的接口上) //单一指责要求的是类和接口的指责单一,注重的是指责,这是业务逻辑的划分。而接口隔离原则要求接口方法尽量少。提供给几个模块就应该有几个接口,而不是建立一个庞大臃肿的接口,容纳所有的客户访问。 class Program { static void Main(string[] args) { BluetoothMouse mouse = new BluetoothMouse(); USBMouse usbmouse = new USBMouse(); } } //蓝牙鼠标类,继承了鼠标接口,蓝牙接口 public class BluetoothMouse : IMouse, IBluetooth { public void LeftClick() { throw new NotImplementedException(); } public void RightClick() { throw new NotImplementedException(); } public void Move() { throw new NotImplementedException(); } public void BluetoothConnect() { throw new NotImplementedException(); } } //USB标类,继承了鼠标接口,USB接口 public class USBMouse : IMouse, IUSB { public void LeftClick() { throw new NotImplementedException(); } public void RightClick() { throw new NotImplementedException(); } public void Move() { throw new NotImplementedException(); } public void USBConnect() { throw new NotImplementedException(); } } //鼠标的接口,对于鼠标本身来说,是肯定包含这左右点击,移动三个方法的 //至于蓝牙连接,还是USB连接,这是外部的连接方式,应该隔离开来(这样其他设备也可以继承这些接口,防止代码冗余复杂),而不是全都写在IMouse这个接口里面 //有人可能会想,move的方式有红外和滑轮这两种方式,是不是应该move也提取出接口隔离出来? //这需要具体分析,在这个案例里是没有必要的,从鼠标类应用的层面看,move是鼠标内部的方法,并没有外部对接,就算提取出来接口,在这个应用层面也没有用处,只会增加复杂度。 //如果我们业务要更细化鼠标类(例如模拟生产制造鼠标),深入各个鼠标的模块组件,可能就有必要将move的接口隔离。 public interface IMouse { void LeftClick(); void RightClick(); void Move(); //应该将下面两个接口隔离,因为他们是外部接口 //如果不隔离,有些鼠标明明只支持USB连接,你还必须实现一个空的蓝牙连接方法? //void BluetoothConnect(); //void USBConnect(); } public interface IBluetooth { void BluetoothConnect(); } public interface IUSB { void USBConnect(); } }
相关文章推荐
- 判断字符串的字符数
- ●导出excel(NPOI)
- 格式的输入与输出
- Android 判断及监听网络连接状态
- VMware CentOS自动联网配置
- AndroidStudio中删除module
- 计算机组成.人机转换大字典.几种字符编码
- WordPress主题 Olam 资源下载数字下载高级商城中文主题[v1.3版]
- 在Ubuntu10.10下升级内核到2.6.36使用systemtap
- java 异步上传文件
- python 基于次世代验证码识别系统的小demo
- [python] can not find app ,module
- 2016/05/17 庄家对敲+筹码
- 个人练习 - 单元测试练习
- 网络基础知识
- 第三次课总结
- iOS开发之AsyncSocket使用教程
- InvokeRequired和Invoke
- Tornado
- [小知识点]绝对路径与相对路径.