开闭原则
定义:类的改动是通过增加代码进行的,而不是修改源代码。
解决方案:使用多态,重写来改动,从而实现功能多样性
依赖反转原则
定义:依赖于抽象(接口),不要依赖具体的实现(类),也就是针对接口编程。
解决方案:定义接口解耦
接口隔离原则
定义:不应该强迫客户的程序依赖他们不需要的接口方法。一个接口应该只提供一种对外功能,即调用者不能依赖一个过大
的接口,调用者从来没有使用到这个接口中的某些成员(但是必须实现),就违反了接口隔离原则
解决方案:将大接口拆分成多个单一功能的小接口,实现接口隔离
interface IVehicle
{
void Run();
}
class Car : IVehicle
{
void Run()
{
Console.WriteLine("Car is Runing");
}
}
class Truck :IVehicle
{
void Run()
{
Console.WriteLine("Truck is Runing");
}
}
interface ITank
{
void Fire();
void Run();
}
class LightTank : ITank
{
void Run()
{
Console.WriteLine("Boom");
}
void Fire()
{
Console.WriteLine("kai kai");
}
}
class HeaveyTank : ITank
{
void Run()
{
Console.WriteLine("Boom Boom ");
}
void Fire()
{
Console.WriteLine("kai kai kai");
}
}
class Driver
{
public IVehicle _vehicle;
public Driver(IVehicle vehicle)
{
_vehicle = vehicle;
}
void Drive()
{
_vehicle.Run();
}
}
int mian()
{
Driver driver = new Driver(new Car());
driver.Drive(); //开汽车 没问题
Driver driver = new Driver(new LightTank());
driver.Drive(); //开坦克 有问题 LightTank 没有继承Ivehicle接口
}
原因:ITank接口太大了
解决方法:将ITank接口拆分成IVehicle, 和IWeapon(Fire方法属于武器类)
interface ITank
{
void Fire();
}
interface IVehicle
{
void Run();
}
interface Itank : IWeapon, IVehicle
{
}
int mian()
{
Driver driver = new Driver(new Car());
driver.Drive(); //开汽车 没问题
Driver driver = new Driver(new LightTank());
driver.Drive(); //开坦克 没问题,ITank继承了IVehicle接口
}
这样就符合了接口隔离原则,调用者不会多调(即不依赖其不用的接口),