//下次想卖DC电源产品,就不得不在PowerSupplySeller类写入一个重载版的Sell方法,违背了开闭原则
}
}
正确的C#代码如下(只需对public void Sell(ACPowerSupply powerSupply)进行修改即可):
class PowerSupplySeller
{
public void Sell(PowerSupply powerSupply)
{
//卖AC或DC电源
}
}
客户端代码如下:
class Program
{
static void Main(string[] args)
{
PowerSupplySeller seller = new PowerSupplySeller();
seller.Sell(new ACPowerSupply());
seller.Sell(new DCPowerSupply());
}
}
以上不仅仅体现在形参上,还体现在方法或属性的返回值、字段类型等。
四、里氏替换原则
简述:可以使用父类的类型来代替子类的类型,但不改变子类的行为,继承必须确保父类所拥有的性质在子类中仍然成立。
C#代码如下:
class Meter
{
public double Voltage
{
get
{
//模仿返回一个值,这里以5.01V为准
double value = 5.01;
Console.WriteLine($"DigitalMeter,Voltage:{value}");
return value;
}
}
public double Current
{
get
{
//模仿返回一个值,这里以1.001A为准
double value = 1.001;
Console.WriteLine($"DigitalMeter,Current:{value}");
return value;
}
}
}
class DigitalMeter: Meter
{
}
class DCPowerSupply : Meter
{
public double Voltage
{
get
{
//模仿返回一个值,这里以12.02V为准
double value = 12.02;
Console.WriteLine($"DCPowerSupply,Voltage:{value}");
return value;
}
}
public double Current
{
get
{
//模仿返回一个值,这里以2.002A为准
double value = 2.002;
Console.WriteLine($"DCPowerSupply,Current:{value}");
return value;
}
}
}
客户端代码如下:
class Program
{
static void Main(string[] args)
{
Meter meter1 = new DigitalMeter();
Meter meter2 = new DCPowerSupply();
var voltage1 = meter1.Voltage;
var voltage2 = meter2.Voltage;
var current1 = meter1.Current;
var current2 = meter2.Current;
}
}
运行结果如下:
从以上可以看出,本来为DCPowerSupply的类,既然输出了Meter的信息,这就违背了里氏替换原则。
新修改的代码如下:
interface IMeter
{
double Voltage { get; }
double Current { get; }
}
class Meter: IMeter
{
public double Voltage
{
get
{
//模仿返回一个值,这里以5.01V为准
double value = 5.01;
Console.WriteLine($"DigitalMeter,Voltage:{value}");
return value;
}
}
public double Current
{
get
{
//模仿返回一个值,这里以1.001A为准
double value = 1.001;
Console.WriteLine($"DigitalMeter,Current:{value}");
return value;
}
}
}
class DigitalMeter: Meter
{
}
class DCPowerSupply : IMeter
{
public double Voltage
{
get
{
//模仿返回一个值,这里以12.02V为准
double value = 12.02;
Console.WriteLine($"DCPowerSupply,Voltage:{value}");
return value;
}
}
public double Current
{
get
{
//模仿返回一个值,这里以2.002A为准
double value = 2.002;
Console.WriteLine($"DCPowerSupply,Current:{value}");
return value;
}
}
}
客户端代码如下:
class Program
{
static void Main(string[] args)
{
IMeter meter1 = new DigitalMeter();
IMeter meter2 = new DCPowerSupply();
var voltage1 = meter1.Voltage;
var voltage2 = meter2.Voltage;
var current1 = meter1.Current;
var current2 = meter2.Current;
}
}
运行结果如下: