继承,多态和封装

继承

That’s when one class inherits behavior from another class, and can then change that behavior if needed.

Inheritance lets you build classes based on other classes, and avoid duplicating and repeating code.

But they have coupled together.

因此在设计模式里,继承是个不太受待见的东西。有句话说“has-a can better than is-a”.


多态

Polymorphism is closely related to inheritance. When one class inherits from another, then polymorphism allows a subclass to stand in for the superclass.

多态这东西在设计中很不错,因为它实现了对象的行为在runtime时是可变的。

例如下面的代码,Apple类继承了Fruit类,同时也实现了CanEat接口:

public class Apple extends Fruit implements CanEat {...}

对于Apple的实例,下面三种写法都成立:

Apple a = new Apple();
Fruit f = new Apple();
CanEat c = new Apple();
而Fruit的另外一个子类pear也可以写成Fruit f = new Pear();的形式,且调用f上的方法时表现出梨的特性。

封装

Encapsulation is when you hide the implementation of a class in such a way that it is easy to use and easy to change. It makes the class act as a black box that provides a service to its users, but does not open up the code so someone can change it or use it the wrong way. Encapsulation is a key technique in being able to follow the Open-Closed principle

封装的另外一个概念就是将代码中的易变部分和不变部分隔离开,以尽可能的让易变部分不影响不变部分。


delegate

composition



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值