以下两个设计原则的区别是什么?
这两个原则说的是相同的东西,但有两种不同的方式。
发布于 2011-01-04 19:16:51
接口是具体类的抽象,因此2是1的子集。原则1具有更广泛的适用性(您可以将它用于任何类型的接口,而不仅仅是面向对象编程中使用的接口)。
发布于 2011-01-04 19:18:57
他们用不同的话说同样的话。
您应该编写类,以便它依赖于抽象的想法(如接口),而不是一个想法的具体实现。这使您可以分段地更改行为,而不必重写整段代码。
见药物注射。
示例:
public class Chef : IResturauntWorker 
{
    // This is an example of writing to an interface instead of an
    // an implementation.  Because the Chef class implements the 
    // IResturauntWorker interface, the chef can be swapped in with other
    // resturaunt workers like bussers or waiters.
    public void Chop(Carrot c)
    {
        // code to chop a carrot
        // this is an example of depending on an implementation
        // because Carrot is a concrete class, this method can 
        // only be used with a Carrot
    }
    public void Chop(IVegetable c)
    {
        // code to chop a Vegetable
        // this is an example of depending on an abstraction
        // because IVegetable is a abstraction of an idea 
        // (a vegetable, in this case), this method can be
        // used with any class that implements IVegetable,
        // including carrots, celery, onions, etc.
    }
}发布于 2011-01-05 14:34:58
接口只不过是提供了通信的手段,不同类型的实现抽象,只是用某种抽象方法创建泛型类。
https://stackoverflow.com/questions/4597414
复制相似问题