gpt4 book ai didi

design-patterns - 对象适配器模式和类适配器模式的区别

转载 作者:行者123 更新时间:2023-12-03 12:02:26 26 4
gpt4 key购买 nike

如何决定何时使用对象适配器以及何时使用类适配器?

问题陈述:
创建社交网站并提供从 facebook、google plus 和 orkut 导入的功能。我无法决定是使用对象适配器还是类适配器。

我看过Adapter Pattern: Class Adapter vs Object Adapter ,但无法理解差异的本质。

最佳答案

主要区别:

  • 类适配器 使用继承并且只能包装一个 类(class) .它不能包装接口(interface),因为根据定义它必须从某个基类派生。
  • 对象适配器 使用组合并且可以包装类或接口(interface),或两者兼而有之。它可以做到这一点,因为它包含作为私有(private)封装成员的类或接口(interface)对象实例 它换行了。

  • 差异是微妙的。通常后一种方法(有利于 composition over inheritance )是更可取的,如我将在此处引用的链接中所述:

    Object-Oriented Programing (OOP) has too well known candidates for thereuse of functionality: Inheritance (whitebox reuse) and Composition(blackbox reuse). If you try to reuse code by inheriing from a classyou will make the subclass dependent on the parent class. This makes asystem in many cases unnecessarily complex, less testable and makesthe exchange of functionality at run time unnecessarily hard. As a [Clean Code Developer]you should follow the Liskov Substitution Principle (LSP) when youneed to decide if inheritance is appropriate.

    Composition means that one class uses another. You will furtherpromote decoupling by defining the interfaces clearly. That will alsogive you the advantage that implementations can be easily replaced. Sobefore you start applying the Liskov Substitution pronciple, thinkabout the Favour Composition over Inheritance concept and askyourselve why you shouldn't prefer composition right away.

    "Because inheritance exposes a subclass to details of its parent'simplementation, it's often said that 'inheritance breaksencapsulation'". (Gang of Four 1995:19)

    关于design-patterns - 对象适配器模式和类适配器模式的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9978477/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com