Head First Design Pattern读书笔记一 Strategy Pattern

来源:互联网 发布:库存优化方案 编辑:程序博客网 时间:2024/05/17 08:06

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.

       策略模式即是用于一种方法会有多种具体的表现形式,如何使得对象调用具体的方法。最重要的地方,就是要通过分析,提取出变与不变的方法,并将变的方法给另外封装好,再利用多态的性质,来确定调用是那个方法类的方法。

在本书中,就是指玩具鸭有flyquack两种方法,但是对于具体的玩具鸭则可能会有不同的flyquack方法,这样就需要将flyquack这两种变的行为给提取出来,并封装在各自的类中,根据面向接口而非实现编程原则,需要建立FlyBehaviorQuackBehavior两个抽象类,具体的方法则在具体类中实现,而在client端,也就是在Duck中,则需要使用到组合,即添加两个行为flyquack的实例变量,当然只需要使用到抽象类。同时还可以添加set方法,用于在运行时通过传递的参数,来调用具体方法对象中的方法,简而言之,即是如下所示:

 

       Behavior为抽取出来的方法抽象类,operationclient所需要调用的方法,其方法的具体实现由BehaviorType1BehaviorType2中的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的方法。

原创粉丝点击