I've been using this tutorial to look into the Strategy pattern. I receive the output he talks about, but it seems like there is no option to use the digHole() method. When I call the method in the Dog() constructor it works though.
My guess is this happens because I need to implement a way to save the ability to dig in the Animal class (like the flying ability), am I correct in this? Does this also mean that for every action I want an animal to take, I should compose it in the Animal class, create an interface with the ability and then create two classes who implement that ability, meaning the ability is either implemented or it isn't?
I also have some troubles with formulating the main thought behind the Strategy pattern. Currently I'm looking at it as 'Encapsulate all actions and compose them together in one main class'. How accurate/fitting is this?
public class Animal {
public Flies flyingType;
public String tryToFly() {
return flyingType.fly();
}
public void setFlyingAbility(Flies newFlyType) {
flyingType = newFlyType;
}
}
public class Dog extends Animal {
public Dog() {
super();
setSound("Bark");
flyingType = new CantFly();
}
public void digHole() {
System.out.println("Dug a hole");
}
}
public interface Flies {
String fly();
}
class ItFlies implements Flies {
public String fly() {
return "Flying high";
}
}
class CantFly implements Flies {
public String fly() {
return "I can't fly";
}
}