Design Principle
Indentify the aspects of your application that vary and separate them from what stays the same。
Another way to think about this principle:take the parts that vary and encapsulate them,so that later you can alter or extend the parts that vary without affecting those that don’t.
实际上就是将应用中,变与不变的部分分离。封装变化的部分,便于以后修改和复用。
Program to an interface,not an implementation.
Has-A can be better than Is-A
We’d rather use composition rather than inherit.
Design Principle:Favor composition over inheritance.
Using composition gives us a lot more flexibility.Not only does it let us encapsulate a family of algorithms into their own set of classes,but it also lets us change behavior at runtime as long as the object we’re composing with implements the correct behavior interface.In this book’s example,first we added two instance variables of the flybehavior and quackbehavior into the duck,In the duck class,we added two method to set behavior,in the concrete class we can use those methods to set behavior dynamically.
The Strategy Pattern defines a family of algorithms,encapsulate each one,and makes them interchangeable.Strategy lets the algorithm vary independently from clients that use it.
策略模式即是用于一种方法会有多种具体的表现形式,如何使得对象调用具体的方法。最重要的地方,就是要通过分析,提取出变与不变的方法,并将变的方法给另外封装好,再利用多态的性质,来确定调用是那个方法类的方法。
在本书中,就是指玩具鸭有fly和quack两种方法,但是对于具体的玩具鸭则可能会有不同的fly和quack方法,这样就需要将fly和quack这两种变的行为给提取出来,并封装在各自的类中,根据面向接口而非实现编程原则,需要建立FlyBehavior和QuackBehavior两个抽象类,具体的方法则在具体类中实现,而在client端,也就是在Duck中,则需要使用到组合,即添加两个行为fly和quack的实例变量,当然只需要使用到抽象类。同时还可以添加set方法,用于在运行时通过传递的参数,来调用具体方法对象中的方法,简而言之,即是如下所示:

Behavior为抽取出来的方法抽象类,operation为client所需要调用的方法,其方法的具体实现由BehaviorType1和BehaviorType2中的opertion实现。在Client中
Public abstract class Client {
Behavior behavior;
public void setBehavior(Behavior _behavior) {
This.behavior = _behavior;
}
public abstract void diplay();
public void performanceBehavior() {
behavior.operation();
}
}
这样在Client1中直接可以使用setBehavior(Behavior behavior)方法来调用具体behavior的方法。
博客介绍了设计原则,强调将应用中变与不变的部分分离,封装变化部分。还阐述了策略模式,即定义算法族并封装使其可互换,让算法独立于使用它的客户端。以玩具鸭为例,说明如何通过分析提取变与不变的方法,利用多态确定调用方法。
2401

被折叠的 条评论
为什么被折叠?



