[Design Pattern] Strategy

[Design Pattern] Strategy

範例參考至 Head First Design Patterns

IFlyBehavior


public interface IFlyBehavior {
	public void fly();
}

FlyNoWay


public class FlyNoWay implements IFlyBehavior
{
	public void fly()
	{
		System.out.println("I can't fly!!");
	}
}

FlyWithWings


public class FlyWithWings implements IFlyBehavior{
	public void fly()
	{
		System.out.println("I'm flying!!");
	}
}

IQuackBehavior


public interface IQuackBehavior {
	public void quack();
}

Quack


public class Quack implements IQuackBehavior{
	public void quack()
	{
		System.out.println("Quack");
	}
}

MuteQuack


public class MuteQuack implements IQuackBehavior{
	public void quack()
	{
		System.out.println("<< Silence >>");
	}
}

Squeak


public class Squeak implements IQuackBehavior{
	public void quack()
	{
		System.out.println("Squeak");
	}
}

Duck


public abstract class Duck {
	IFlyBehavior iFlyBehavior;
	IQuackBehavior iQuackBehavior;
	public Duck(){}
	public abstract void display();
	public void performFly()
	{
		iFlyBehavior.fly();
	}
	public void perFormQuack()
	{
		iQuackBehavior.quack();
	}
	public void SetFlyBehavior(FlyBehavior fb)
	{
		iFlyBehavior = fb;
	}
	public void SetQuackBehavior(QuackBehavior qb)
	{
		iQuackBehavior = qb;
	}
	public void swim()
	{
		System.out.println("All ducks float, even decoys!");
	}
}

RobotDuck


public class RobotDuck extends Duck{
	public RobotDuck()
	{
		iQuackBehavior = new MuteQuack();
		iFlyBehavior = new FlyNoWay();
	}
	public void display()
	{
		System.out.println("I'm a real Mallard duck");
	}
}

MallardDuck


public class MallardDuck extends Duck{
	public MallardDuck()
	{
		iQuackBehavior = new Quack();
		iFlyBehavior = new FlyWithWings();
	}
	public void display()
	{
		System.out.println("I'm a real Mallard duck");
	}
}

MiniDuckSimulator


public class MiniDuckSimulator {
	public static void main(String[] args)
	{
		Duck mallard = new MallardDuck();
		mallard.perFormQuack();//perFormQuack() from Duck class
		mallard.performFly();
		
		System.out.println("-----------------------------------");
		System.out.println("change before...");
		mallard = new RobotDuck();
		mallard.perFormQuack();//change before the behavior 
		mallard.performFly();
		
		System.out.println("change after...");
		mallard.SetFlyBehavior(new FlyWithWings());
		mallard.SetQuackBehavior(new Quack());
		mallard.perFormQuack();//before change the behavior 
		mallard.performFly();
	}
}

Output:

Quack
I'm flying!!
-----------------------------------
change before...
<< Silence >>
I can't fly!!
change after...
Quack
I'm flying!!