惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Google DeepMind News
Google DeepMind News
Stack Overflow Blog
Stack Overflow Blog
Hugging Face - Blog
Hugging Face - Blog
博客园_首页
T
The Blog of Author Tim Ferriss
博客园 - 叶小钗
N
Netflix TechBlog - Medium
腾讯CDC
C
Check Point Blog
P
Proofpoint News Feed
Engineering at Meta
Engineering at Meta
GbyAI
GbyAI
S
SegmentFault 最新的问题
F
Fortinet All Blogs
美团技术团队
U
Unit 42
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园 - 司徒正美
F
Full Disclosure
Recorded Future
Recorded Future
D
DataBreaches.Net
博客园 - 【当耐特】
Martin Fowler
Martin Fowler
J
Java Code Geeks
I
InfoQ
Y
Y Combinator Blog
A
About on SuperTechFans
AI
AI
爱范儿
爱范儿
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Forbes - Security
Forbes - Security
W
WeLiveSecurity
M
MIT News - Artificial intelligence
雷峰网
雷峰网
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Simon Willison's Weblog
Simon Willison's Weblog
Schneier on Security
Schneier on Security
The GitHub Blog
The GitHub Blog
Security Archives - TechRepublic
Security Archives - TechRepublic
aimingoo的专栏
aimingoo的专栏
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
G
GRAHAM CLULEY
Know Your Adversary
Know Your Adversary
Latest news
Latest news
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
D
Docker
Recent Commits to openclaw:main
Recent Commits to openclaw:main
量子位
V2EX - 技术
V2EX - 技术
Project Zero
Project Zero

博客园 - flyingchen

gcc的一个困惑 敏捷项目组 javascript string to date - flyingchen 熟悉了以下VIM指令,你会爱死她的 ajax应用如何做好seo - flyingchen - 博客园 nestful - ruby http-rest 客户端 分析 Linux Commands Cannot find autoconf. Please check your autoconf installation pecl报错(1) - flyingchen - 博客园 关于角色访问控制(RBAC) post xml 通过 simplexml_load_string 解析问题 - flyingchen awk学习 php实现单件模式总结(持续更新) 激动网 PHP高级开发工程师 招聘 rsync的命令格式 rsync从linux到linux的文件同步备份 zend + apache + config stop words mmseg 安装错误 error: ’strncmp’ was not declared in this scope
Liskov替换原则与继承
flyingchen · 2010-04-30 · via 博客园 - flyingchen

如果一件事情你不能用自己的语言说清楚,那只能说你没有真正的理解它。“只可意会不可言传”在科学领域应该只是一种假象。

----废话结束----

   一直以来都认为自己搞清楚了何时用继承,何时用聚合,也清楚了所谓的Liskov替换原则的意义。直到今天看完了“高效程序员的十个习惯”以后才明白,才认识到自己以前的理解是

混沌含糊的。

      何时用继承呢?大部分情况我们仅仅为了利用另一个已存在的类的功能而继承,或者几个类有功能近似,或者代码重复,就提取个公用类,然后再继承之。长期以来,我都是这样的理解
。如果从实现上来说,这样是没有问题的,复用了代码,减少了重复。但如果用Liskov原则来审查设计就会发现,这样的实现其实是很欠妥的。是滥用继承的一种。下面我们具体分析。

      Liskov原则要求我们,“任何能用基类的地方都应该可以无差别的使用其继承类替换”。“滥用的继承”模式也可以从实现层面遵循此规则,因为它也是继承。但由于脱离了继承的本意,这

样的实现最终会得到差强人意的结果。比如基类中A方法是要求”站力“,而继承B却实现成了”坐下“,从语法和实现上都没有问题,但却违背了设计继承的本意。这也是滥用继承也不会被

有效察觉的原因:它不会主动报错,错误在潜台词里。

    继承,应该”不要求更多,不承诺更少“,也就是语意上的一致,而不仅仅是方法签名,只有IS-A的情况才可以使用继承。

    类似上面所说的这些”被滥用的继承“,最好的方式就是改造成聚合实现。虽然可能稍微麻烦一点点,但这满足设计的基本原则。

    通过对Liskov的理解,让设计更清晰,遵从对象本意设计,而不是语法与技巧。