我正在考虑对接口而不是具体类进行编程,但我有一个疑问:任何接口方法都应该能够保存对具体类的引用吗?
假设以下场景:
1)
public interface AbsType1 {
public boolean method1(int a); // it's ok, only primitive types here
}
2)
public interface AbsType2 {
public boolean method2(MyClass a); // I think I have some coupling here
}
我应该在这里选择不同的设计以避免后者吗?例如
public interface MyInterface {} // yes, this is empty
public classe MyClass implements MyInterface {
// basically identical to the previous "MyClass"
}
public interface AbsType2 {
public boolean method2(MyInterface a); // this is better (as long as the
// interface is really stable)
}
但是仍然有一些事情不能说服我......我对声明一个空接口感到不舒服,尽管我看到其他人这样做。也许抽象类在这里会更好用?
我有点困惑。
编辑:
好的,我将尝试通过举例来更具体。假设我正在设计一个 ShopCart,我当然想将商品添加到购物车:
public interface ShopCart {
public void addArticle(Article a);
}
现在,如果 Article 是一个具体的类,如果它的实现随时间发生变化怎么办?这就是为什么我可以考虑将其设为接口的原因,但话又说回来,它可能至少在语义层面上不合适,因为接口应该指定行为而文章没有(或几乎没有......我猜它是一种实体班级)。
所以,我现在可能最终得出的结论是,在这种情况下,让 Article 成为一个抽象类将是最好的事情......你怎么看?