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.是事物尽量的抽象化,提取共同特性
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值