Posted: July 7th, 2010 | Author: Christopher Vigliotti | 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");
}
} |
Posted: July 6th, 2010 | Author: Christopher Vigliotti | Filed under: Design Patterns, O-O | 1 Comment »
Over the last few days I’ve been sinking my teeth into Head First Design Patterns
. I’m really enjoying both learning about Design Patterns as well as slinging some Java code.