Im new in OOP programming and C++ and Im currently into learning design patterns.
Just grab the Head First Design Patterns book to learn from. Its actually great and Im already getting hold into the basic concepts.The first chapter talks about programming to an interface rather an implementation. Unfortunately for me though, the examples uses java.
Below is the java code sample from the books using "interface", I understand that this cannot be directly ported in C++. Ive tried to implement C++'s abstract base class. But Im lost especially in setting the QuackBehavior dynamically.
Can C++ virtual functions definition be dynamic? Can someone please show me how to best way to port this java code into C++? I need this to be sure im on the right track in learning OOP. Thanks!
//FlyBehavior.java
public interface FlyBehavior{
public void fly(); //the interface that all flying behavior classes implement
}
public class FlyWithWings implements FlyBehavior {
public void fly(){
System.out.println("Im flying!"); //flying behavior implementation for ducks that do fly
}
}
//QuackBehavior.java
public interface QuackBehavior{
public void quack();
}
public class Quack implements QuackBehavior {
public void quack() {
System.out.println("Quack");
}
}
public class Squeak implements QuackBehavior {
public void quack() {
System.out.println("Squeak");
}
}
public class MuteQuack implements QuackBehavior {
public void quack() {
System.out.println("<<SILENCE>>");
}
}
//duck.java
public abstract class Duck{
FlyBehavior flyBehavior;
QuackBehavior quackBehavior;
public Duck(){
}
public abstract void display();
public void performFly(){
flyBehavior.fly();
}
public void performQuack(){
quackBehavior.quack();
}
public void setFlyBehavior(FlyBehavior fb){
flyBehavior = fb;
}
public void setQuackBehavior(QuackBehavior qb){
quackBehavior = qb;
}
public void swim(){
System.out.println ("All duck float, even decoys");
}
}
//MallardDuck.java
public class MallardDuck extends Duck{
public MallardDuck(){
quackBehavior = new Quack();
flyBehavior = new FlyWithWings();
}
public void display(){
System.out.println("Im a real Mallard duck");
}
}
//miniducksim.java
public class MiniDuckSimulator{
public static void main (String[] args){
Duck mallard = new MallardDuck();
mallard.setQuackBehavior(new Squeak()); // this is where im lost
//how can definition of a virtual functions in C++ be dynamic?
mallard.performQuack();
mallard.performFly();
}
}