我一直在尝试弄清楚Liskov替换原理和接口隔离原理,但我对以下示例有些困惑。
假设我们有一个Vehicle带有几个属性的基类,以及一个IVehicle在IVehicle该类中实现的接口。
我们有两个子类,Car&Motorcycle。Car从Vehicle继承并实现IVehicle接口。Motorcycle从Vehicle继承并也实现IVehicle,但是Motorcycle具有额外的属性,该属性也添加到了IMotorcycle在Motorcycle该类中实现的新Interface中。
让我通过编写代码来澄清它:
public interface IVehicle
{
string Brand { get; set; }
string Model { get; set; }
int HorsePower { get; set; }
}
public interface IMotorcycle
{
DateTime DateCreated { get; set; }
}
public abstract class Vehicle : IVehicle
{
public string Brand { get; set; }
public string Model { get; set; }
public int HorsePower { get; set; }
}
public class Car : Vehicle, IVehicle
{ }
public class Motorcycle : Vehicle, IVehicle, IMotorcycle
{
public DateTime DateCreated { get; set; }
}
public class Start
{
public IVehicle DoSomeStuff()
{
//Does some stuff
//Based on logic we either return
//a new Car or Motorcycle
//but if I return a motorcycle how would I be able to
//access the DateCreated attribute since I'm returning IVehicle
//I guess I have to cast it but is it a good practice to do that
//or am I setting up everything incorrect?
return new Motorcycle();
}
}
我的问题:如果我们说一个类,该类Start具有返回IVehicle(public IVehicle DoSomeStuff())的方法。根据逻辑,我们将返回newCar或Motorcycle。如果我们返回一个新值,Car因为它仅实现了IVehicle接口,我们将能够访问所有属性,但是假设我们返回一个新值,Motorcycle该方法将能够在.DateCreated不强制转换的情况下访问该属性,
有没有一种方法可以更好地实现此目的,而不是拥有共同的接口,或者我错过了任何事情?
慕神8447489
相关分类