策略模式
/**
* 策略接口,定义飞行行为
*/
public interface FlyingStragety {
void fly();
}
public abstract class Duck {
private FlyingStragety fs;
public void setFs(FlyingStragety fs) {
this.fs = fs;
}
public void behavior(){
fs.fly();
}
}
public class SingWing implements FlyingStragety {
private String name;
public SingWing(String name) {
this.name = name;
}
@Override
public void fly() {
System.out.println(name + ": 单翅膀飞行");
}
}
public class DoubleWing implements FlyingStragety{
private String name;
public DoubleWing(String name) {
this.name = name;
}
@Override
public void fly() {
System.out.println(name+": 双翅飞行");
}
}
public class PsyDuck extends Duck {
public PsyDuck(String name) {
super();
super.setFs(new SingWing(name));
}
}
public class UglyDuck extends Duck{
public UglyDuck(String name) {
super();
super.setFs(new DoubleWing(name));
}
}
public static void main(String[] args) {
Duck uglyDuck = new UglyDuck("丑小鸭");
Duck psyDuck = new PsyDuck("可达鸭");
testFly(uglyDuck);
testFly(psyDuck);
}
public static void testFly(Duck duck){
duck.behavior();
}
![这里写图片描述](https://img-blog.csdn.net/20170414215941167?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvY29kZXN1cGVyTWFuMTMxNA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)