Chapter 1: Welcome to Design Patterns
Strategy pattern: defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
1, 抽取出对象共有的属性和特有的属性,共有的属性可以做成继承关系,不同的子类对象有自己不同的实现;特有的属性可以做成接口的形式,只有特定的对象去实现相应的接口就可以了,这样避免了更改父类会导致影响全部子类的问题。
conclusion: 如果实现接口的子类较多,当接口行为发生变化时,需要在各个子类中都去做相应的修改,这点会带来比较严重的问题!
设计原则: program to an interface, not an implemention.(interface --- interface, abstract class)
2, 找到那些changed的属性, 从原先的类中抽取出来,做成单独的类(接口)
3, 巧妙使用get/set的方式: 比如父类中有fly的抽象方法(Duck), 子类ColorDuck需要摸个Behavior的引用behavior, 有两种方式初始化behavior, 1)创建beavhor的对象,但这样会设计到具体的类 2)使用set/get来巧妙规避第一种方式引起的问题,使用set**方式传进去这个具体对象的接口来初始化这个对象。
设计原则: Favor composition over inheritance.