在我的项目中,我想实现SOLID原则,这样我的代码可能更容易测试和以后的扩展。为此,我很好奇是否可以使用Liskov的替代原则,让生产类和测试类都继承一个接口,并代替它的作用,从而使代码的测试变得更容易。
接口+对象类
public interface Iinterface {
int commonVariable { get; set; }
}
public class ProductionClass : IInterface{
public commonVariable { get; set; }
//Production variables + functions
public ProductionClass() {}
}
public class TestClass : IInterface {
public commonVariable { get; set; }
//Test variables + functions
public TestClass() {}
}
领域模型
public class DomainModel() {
//Could object be either of ProductionClass or TestClass without breaking my database?
public virtual IInterface object { get; set; }
}
由于ProductionClass和TestClass都继承了IInterface,我知道任何一个类的对象都可以放在IInterface变量中。
然而,在构建数据库时,IInterface对象是否有效?
它是否能容纳 都 的数据,还是只是定义接口时指定的数据?
如果我试图在对象中插入一个不同类的对象会发生什么?表的列会被新类的变量覆盖吗?
在这种情况下,我是否应该尝试制作TestClass呢?
你展示的类设计并不是LSP(Liskov Substitution Principle)的例子。它是DI(依赖反转)的一个例子:具体内容(DomainModel
)取决于抽象的(IInterface
).
要有一个LSP的情况下,你需要。
class Base { }
class Derived : Base { }
void Process(Base item)
{
// here, the method shall not care whether 'item' is in fact
// an instance of 'Base' or 'Derived'
}
"继承一个接口 "是不正确的。"实施 一个接口 "是正确的。类不能继承接口,只能实现接口。
拥有一个变量(或一个字段,或一个属性),类型为 IInterface
,你只能告诉你以下几点:我所拥有的对象。实现该接口. 你对对象的具体类型一无所知--它是否是一个。TestClass
, a ProductionClass
或 ThirdPartyClass
(当然,除非你明确地检查类型)。对象内部可能是完全不同的。它可能包含你所需要的所有数据,也可能根本没有数据。
作为一个设计建议:使用接口来抽象你的服务和业务实体。使用具体类型(POCO)来表示你的DTO(数据传输对象)。