对象适配器模式和类适配器模式之间的区别 [英] Difference between object adapter pattern and class adapter pattern

查看:709
本文介绍了对象适配器模式和类适配器模式之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to decide when to use object adapter and when to use class adapter?

问题陈述:
创建社交网站并提供导入功能从Facebook,谷歌和orkut。我无法决定是否使用对象适配器或类适配器。

Problem statement: To create social networking web site and provide import functionality from facebook, google plus and orkut. I am unable to decide whether to use object adapter or class adapter.

我已经看过适配器模式:类适配器与对象适配器,但无法理解差异的本质。

I have had look at Adapter Pattern: Class Adapter vs Object Adapter, but could not understand the essence of the difference.

推荐答案

主要区别:


  • strong>使用继承,只能包装。它不能包装一个接口,因为根据定义它必须从一些基类派生。

  • Class Adapter uses inheritance and can only wrap a class. It cannot wrap an interface since by definition it must derive from some base class.

对象适配器使用 em>并且可以包装类或接口,或两者兼容。它可以这样做,因为它包含作为私有封装的成员,它包装的类或接口对象实例

差异是微妙的。通常后来的方法(赞成组合继承)是最好的,如我将在这里引用的链接:

The difference is subtle. Usually the later approach (favoring composition over inheritance) is the preferable as explained in the link which I'll quote here:


面向对象编程(OOP)对于
重用来说是非常有名的候选人的功能:继承(白盒重用)和Composition
(黑盒重用)。如果您尝试通过从一个类
中传递来重用代码,那么您将使该子类依赖于父类。这使得
系统在许多情况下不必要地复杂,不可测试,并且使得
在运行时不必要地进行功能交换。作为[Clean Code Developer]
,您应该遵循 Liskov替代原则(LSP)
需要确定继承是否合适时。

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

组合意味着一个类使用另一个类。您将进一步
通过明确界定界面来促进解耦。这也将$ b​​ $ b给你的优势,实现可以很容易地替换。所以
在你开始应用Liskov替代语言之前,认为
关于对于继承概念的偏好组合,并要求
yourselve为什么你不应该喜欢立即组合。

Composition means that one class uses another. You will further promote decoupling by defining the interfaces clearly. That will also give you the advantage that implementations can be easily replaced. So before you start applying the Liskov Substitution pronciple, think about the Favour Composition over Inheritance concept and ask yourselve why you shouldn't prefer composition right away.

因为继承暴露了一个子类,它的父代的
实现的细节,通常被称为'继承破坏
封装'。 (Gang of Four 1995:19)

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

这篇关于对象适配器模式和类适配器模式之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆