您的位置:首页 > 其它

接口隔离原则(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();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: