逖靖寒的世界

每天进步一点点

导航

Head First Design Patterns -- charpter 1

It start with a simple SimUDuck app



But now, we need the ducks to fly

Opps!The RubberDuck fly in the Sky

We can solve the bus in the way

If we add a new class like DecoyDuck
 

•In this class, The DecoyDuck can not quack but also can not fly.So we have to override the quack() function and the fly() function to let the DecoyDuck class do right.
•If we add some more class like this, what a nightmare it would be.

How about an interface ?

What would happened to this design?
 
In this design, we meet the same problem in the last design: We have to override the quack() function and the fly() function to make every class that inheritance the FlyAble and the QuackAble interface.
If we add some more class like this, what a nightmare it would be.
How can we solve this problem?
Someone has already solved your problems

At this point you might be waiting for a Design Patterns to come riding in on a white horse an save the day.
Here’s a simple example of using a polymorphic type

 

Animal animal = new Dog();

animal.MakeSound();

animal = new Cat();

animal.MakeSound();
Implementing the Duck Behavior

How about this design?
 

With this design, other types of objects can reuse out fly and quack behaviors because these behaviors are no longer hidden away in our Duck classes!
And we can add new behaviors without modifying any of our existing behavior classes or touching any of the Duck classes that use flying behaviors.
Ok, It’s time to solve the problem

 
Step 1

  We’ll add two instance variables to the Duck class. 

Step 2

  implement performQuack():

 

  public class Duck {

  QuackBehavior quackBehavior;

    // more

  public void performQuack() {

  quackBehavior.quack();

    } 

  } 

Step 3

  Set the flyBehavior and quackBehavior instance variables.

  public class MallardDuck extends Duck {

     public MallardDuck() {

        quackBehavior = new Quack();

       flyBehavior = new FlyWithWings(); 

     }

  } 

Step 4

  Finish the Main Function

  public class MiniDuckApp {

     public static void main (String[] args) {

        Duck mallard = new MallardDuck();

         mallard.performQuack();

          mallard.performFly();

     }

  }

Congratulations on your first pattern!

 

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. 

Thanks

posted on 2007-04-02 18:12  逖靖寒  阅读(246)  评论(0编辑  收藏  举报