Head First Design Pattern读书笔记一 Strategy Pattern

博客介绍了设计原则,强调将应用中变与不变的部分分离,封装变化部分。还阐述了策略模式,即定义算法族并封装使其可互换,让算法独立于使用它的客户端。以玩具鸭为例,说明如何通过分析提取变与不变的方法,利用多态确定调用方法。

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的方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值