首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >设计原则

设计原则
EN

Stack Overflow用户
提问于 2011-01-04 19:12:43
回答 4查看 167关注 0票数 1

以下两个设计原则的区别是什么?

  1. “程序到接口,而不是实现”和
  2. “依赖于抽象,不依赖于具体的类”。

这两个原则说的是相同的东西,但有两种不同的方式。

EN

回答 4

Stack Overflow用户

发布于 2011-01-04 19:16:51

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

票数 6
EN

Stack Overflow用户

发布于 2011-01-04 19:18:57

他们用不同的话说同样的话。

您应该编写类,以便它依赖于抽象的想法(如接口),而不是一个想法的具体实现。这使您可以分段地更改行为,而不必重写整段代码。

见药物注射。

示例:

代码语言:javascript
运行
复制
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
EN

Stack Overflow用户

发布于 2011-01-05 14:34:58

接口只不过是提供了通信的手段,不同类型的实现抽象,只是用某种抽象方法创建泛型类。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4597414

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档