接口隔离原则:服务调用者不能多要!服务的提供者不能少给这是硬性要求,但是服务的调用者不能多要这是软性要求,实现服务调用者不能多要需要我们在设计时实现。下面是已经设计好的、符合接口隔离原则!下面还有一个不符合接口隔离原则的实例代码。
符合
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp49
{
class Program
{
static void Main(string[] args)
{
Driver driver = new Driver(new Car());
driver.Drive();
}
}
class Driver
{
private IVehicle _vehicle;
public Driver( IVehicle vehicle)
{ // 创建的是IVehicle接口类型,IVehicle接口不包含开炮方法,即使下面ITank接口方法继承了IVehicle,也不包含开炮方法!(是一个概念!!)
_vehicle = vehicle;
}
public void Drive()
{
_vehicle.Run();
//在这里调用不到坦克开炮方法,因为(是一个概念) ITank属于IVehicle 但IVehicle不属于ITruck
}
}
interface IVehicle
{
void Run();
}
class Car : IVehicle
{
public void Run()
{
Console.WriteLine("皮皮虾我们走!");
}
}
class Truck : IVehicle
{
public void Run()
{
Console.WriteLine("卡车!!!");
}
}
interface IWeapon
{
void Fire();
}
interface ITank :IVehicle, IWeapon
{//继承IVehicle,IWeapon 两个接口!下面坦克实例实现了开炮和开车方法。
}
class LightTank : ITank
{
public void Fire()
{
Console.WriteLine("开火!");
}
public void Run()
{
Console.WriteLine("跑!");
}
}
class MediumTank : ITank
{
public void Fire()
{
Console.WriteLine("开火!!");
}
public void Run()
{
Console.WriteLine("跑!!");
}
}
class HeavyTank : ITank
{
public void Fire()
{
Console.WriteLine("开火!!!");
}
public void Run()
{
Console.WriteLine("跑!!!");
}
}
}
下面代码是不符合“接口隔离原则”的,假如我要调用LightTank的Run方法,需要在Driver类里面创建ITank接口的字段和实例,创建成功了之后,还会返回Fire和Run两个方法。但是我只需要Run方法,还有另外一个问题,假如我要调用Car的Run方法呢?还要去改Driver类里面的接口实例。所以下面这段代码功能调用者多调用了一个方法,还有我想调用另外一个接口的方法还需要改接口实例。
不符合
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp49
{
class Program
{
static void Main(string[] args)
{
Driver driver = new Driver(new Car());
driver.Drive();
}
}
class Driver
{
private IVehicle _vehicle;
public Driver(IVehicle vehicle)
{
_vehicle = vehicle;
}
public void Drive()
{
_vehicle.Run();
}
}
interface IVehicle
{
void Run();
}
class Car : IVehicle
{
public void Run()
{
Console.WriteLine("皮皮虾我们走!");
}
}
class Truck : IVehicle
{
public void Run()
{
Console.WriteLine("卡车!!!");
}
}
interface ITank
{
void Run();
void Fire();
}
class LightTank : ITank
{
public void Fire()
{
Console.WriteLine("开火!");
}
public void Run()
{
Console.WriteLine("跑!");
}
}
class MediumTank : ITank
{
public void Fire()
{
Console.WriteLine("开火!!");
}
public void Run()
{
Console.WriteLine("跑!!");
}
}
class HeavyTank : ITank
{
public void Fire()
{
Console.WriteLine("开火!!!");
}
public void Run()
{
Console.WriteLine("跑!!!");
}
}
}