Head First_设计模式_策略模式

package Strategy_Pattern;

/*
 * head first 设计模式  完整代码练习
 * 
 * 1.策略模式(封装算法,让算法之间可以相互代替。<好处:使得算法的变化独立于使用算法的客户。>)
 * 
 * 
 * */

public abstract class Strategy_Pattern_Duck {

	FlyBehaver flyBehaver;
	EatDifference eatDifference;

	// 习惯写空的构造方法
	public Strategy_Pattern_Duck() {
	};

	// 用接口来实现具体的算法
	public void flyPerform() {
		flyBehaver.fly();
	}

	public void eatPerform() {
		eatDifference.eat();
	}

}
package Strategy_Pattern;

interface FlyBehaver {
	// 飞行的方法
	void fly();
}

class FlywhitB implements FlyBehaver {

	@Override
	public void fly() {
		// TODO Auto-generated method stub
		System.out.println("FlywhitB");
	}

}

class FlywhitA implements FlyBehaver {

	@Override
	public void fly() {
		// TODO Auto-generated method stub
		System.out.println("FlywhitA ");
	}

}

package Strategy_Pattern;

public interface EatDifference {

	void eat();
}

class EatApple implements EatDifference {

	@Override
	public void eat() {
		// TODO Auto-generated method stub
		System.out.println("this is duck eatting Apple!");
	}

}

class EatBanana implements EatDifference {

	@Override
	public void eat() {
		// TODO Auto-generated method stub
		System.out.println("this is duck eatting banana!");
	}

}

package Strategy_Pattern;

public class WhiteDuck extends Strategy_Pattern_Duck {
	public WhiteDuck() {

		// 具体的whiteDuck有具体的eat和fly的方法
		flyBehaver = new FlywhitB();
		eatDifference = new EatApple();
	}

	public void sayHello() {
		System.out.println("这是WhiteDuck!");
	}
}

package Strategy_Pattern;

public class Test {

	public static void main(String arg[]) {
		Strategy_Pattern_Duck d = new WhiteDuck();
		d.eatPerform();
		d.flyPerform();
		((WhiteDuck) d).sayHello();

	}
}


 
  


你可能感兴趣的:(设计模式)