`
pan_java
  • 浏览: 286175 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

hand first 设计模式 --策略模式

阅读更多
Duck 的抽象类
public abstract class Duck {

	public abstract void color();

	public abstract void weight();

}


RedDuck(红色的鸭子)

public class RedDuck extends Duck {

	@Override
	public void color() {
		// TODO Auto-generated method stub
		System.out.println("I'M color is red");

	}

	@Override
	public void weight() {
		// TODO Auto-generated method stub
		System.out.println("I'm weight is 5kg");

	}

}


颜色和重量是每个鸭子的共同特性,还有一个其他的特性比如飞行和叫有一个鸭子就不会,玩具鸭就不叫(假设),木头鸭就不会飞.所以我们把变化的东西组合到类里,不使用继承.

飞接口
public interface IFlyAction {
	public void fly();
}


叫接口
public interface IShoutAction {
	public void shout();
}


定制RedDuck飞的动作
public class RedDuckFly implements IFlyAction {

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

	}

}


定制RedDuck的叫
public class RedDuckShout implements IShoutAction {

	@Override
	public void shout() {
		// TODO Auto-generated method stub
		System.out.println("g ,g,g");

	}

}


public abstract class Duck {

	private IFlyAction flyAction;

	private IShoutAction shoutAction;

	public abstract void color();

	public abstract void weight();

         //所有的鸭子都会游泳
	public void swim() {
		System.out.println("i cam swim");
	}

	public void setFlyAction(IFlyAction flyAction) {
		this.flyAction = flyAction;
	}

	public void setShoutAction(IShoutAction shoutAction) {
		this.shoutAction = shoutAction;
	}
	
	public void performFly(){
		flyAction.fly();
	}
	
	public void performShout(){
		shoutAction.shout();
	}

}



测试类
public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		Duck redDuck = new RedDuck();
		//可以动态的定制动作
                  redDuck.setFlyAction(new RedDuckFly());
		redDuck.setShoutAction(new RedDuckShout());
		redDuck.performFly();

	}

}



设计原则:
1.多用组合,少用继承
2.面象接口编程
3.是事物尽量的抽象化,提取共同特性




分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics