首页 > 学院 > 开发设计 > 正文

Head First_设计模式_策略模式

2019-11-14 09:11:46
字体:
来源:转载
供稿:网友
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();	}}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表