The Strategy Pattern

Posted: July 7th, 2010 | Author: | Filed under: Design Patterns | 2 Comments »

I’ve read and coded my way through the first chapter of Head First Design Patterns and enjoyed working with the MiniDuckSimulator sample. The author(s) make a good case for favoring composition over inheritance. I look forward to understanding this concept on a deeper, actionable level as I continue onto Chapter 2. I’ve included some (but not all) of my code from Chapter 1…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/* 
MiniDuckSimulator.java
creates a new instance of MallardDuck and ModelDuck 
and demonstrates the different behaviors of each
*/
public class MiniDuckSimulator{
	public static void main(String[] args){
 
		System.out.println("-- new MallardDuck instance...");		
 
		Duck mallard = new MallardDuck();
		mallard.performQuack();
		mallard.performFly();
 
		System.out.println("-- new ModelDuck instance...");		
 
		Duck model = new ModelDuck();
		model.performFly();
 
		//		now he can fly!
		model.setFlyBehavior(new FlyRocketPowered());
		model.performFly();	
	}
}
1
2
3
4
5
6
7
8
9
10
11
12
/* 
MallardDuck.java
a duck that has wings and can quack
*/
public class MallardDuck extends Duck{
 
	//	constructor
	public MallardDuck(){
		quackBehavior = new Quack();
		flyBehavior = new FlyWithWings();
	}
}
1
2
3
4
5
6
7
8
9
10
11
12
/* 
ModelDuck.java
a duck that cannot fly
*/
public class ModelDuck extends Duck{
 
	//	constructor
	public ModelDuck(){
		flyBehavior = new FlyNoWay();
		quackBehavior = new Quack();
	}
}
1
2
3
4
5
6
7
/*
FlyBehavior.java
the interface!
*/
public interface FlyBehavior {
	public void fly();
}
1
2
3
4
5
6
7
8
9
/*
FlyNoWay.java
implements FlyBehavior
*/
public class FlyNoWay implements FlyBehavior{
	public void fly(){
		System.out.println("I can't fly :(");
	}
}
1
2
3
4
5
6
7
8
9
/*
FlyRocketPowered.java
implements FlyBehavior
*/
public class FlyRocketPowered implements FlyBehavior{
	public void fly(){
		System.out.println("I'm flying with a rocket");
	}
}

2 Comments on “The Strategy Pattern”

  1. 1 Glyn Jackson said at 11:41 am on July 18th, 2010:

    I love the head first books.

    I am also read Design Patterns. I had to read the first chapter on the Strategy Pattern a few times and it really did not make much sense to me until I applied it like you.

    Patterns of Patterns and Factory Pattern really has me stumped at the mo. Would like to see you opinions on them.

    anyone else think of getting this book who has not done any Java I would recommend the head first Java book first. or like me its a good refresher before you start this book.

  2. 2 Christopher Vigliotti said at 1:17 pm on July 21st, 2010:

    I may also take a step back and hack through an introductory Java book before proceeding. Any suggestions?


Leave a Reply