博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

The Strategy Pattern

Posted on 2009-11-19 19:48  Sunny Xu  阅读(135)  评论(0编辑  收藏  举报

The 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.

We will take an example to explain it.

Suppose that we will develop a game with lots of ducks. As we all know, duck can swim and quack. So now  we created one Duck superclass from which all other duck types inherit. We use standard OO techniques and it works well.

However, one day our requirement changes that we have some ducks can fly. Then how will we do? Perhaps we come up an answer to the question that just add a function fly() to the superclass Duck. Although the new requirement has been satisfied, the problem  come into being, too. All ducks can fly now! It's terrible obviously! 

We begin to find another solution. We could take the fly() out of the Duck superclass, and make a Flyable() interface with a fly() method. That way, only the ducks that are supposed to fly will implement that interface and have a fly() method. Good and right solution!

The question has been solved rightly now. But if we see and think in-depth, it is not hard to find that there will be many duplicate code. How many ducks that can fly we will have how many fly() methods to implement! We want to make the code clean and less duplicate codes.  

 We can do like this: We use an interface to represent fly behavior-FlyBehavior  and it has to implementations -FlyWithWings(可以飞) and FlyNoWay(不可以飞). 

In the superclass of Duck, we have a FlyBehavior property and a method performFly. In the subclass we just to initial the FlyBehavior like flyBehavior to call "flyBehavior. FlyWithWings ()" or "flyBehavior. FlyNoWay". It's perfect!