设计原则

时间:2011-01-04 19:12:44

标签: design-patterns

以下两个设计原则之间有什么区别?

  1. “程序到界面,而不是实现”和
  2. “取决于抽象,不依赖于具体的阶级”。
  3. 这两个原则用两种不同的方式说同样的事情。

4 个答案:

答案 0 :(得分:6)

接口是具体类的抽象,因此2.是1的子集。原则1.具有更广泛的适用性(您可以将它用于任何类型的接口,而不仅仅是用于面向对象编程的接口)。

答案 1 :(得分:2)

他们用不同的语言表达同样的意思。

你应该编写你的类,使它依赖于一个抽象的想法(比如一个接口),而不是一个想法的具体实现。这允许您更改行为,而不必重写整个代码块。

参见Dependancy Injection。

示例:

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.
    }
}

答案 2 :(得分:0)

接口只是提供沟通不同类型的实现的意思 抽象只是用一些抽象方法创建泛型类。

答案 3 :(得分:0)

在面向对象的世界中,这些术语经常使用且互换。 接口只不过是抽象和实现,只不过是具体的。