继承
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