public interface FlyBehavior {
void fly();
}
public class FlyGood implements FlyBehavior {
@Override
public void fly() {
System.out.println("飞行能力优秀");
}
}
public class FlyNormal implements FlyBehavior {
@Override
public void fly() {
System.out.println("飞行能力一般");
}
}
public interface SwimBehavior {
void swim();
}
public class SwimGood implements SwimBehavior {
@Override
public void swim() {
System.out.println("游得好");
}
}
public class SwimNormal implements SwimBehavior {
@Override
public void swim() {
System.out.println("游得一般");
}
}
public abstract class Goose {
//策略接口
FlyBehavior flyBehavior;
SwimBehavior swimBehavior;
//其他属性等...
public void setFlyBehavior(FlyBehavior flyBehavior) {
this.flyBehavior = flyBehavior;
}
public void setSwimBehavior(SwimBehavior swimBehavior) {
this.swimBehavior = swimBehavior;
}
}
public class Swan extends Goose{
public Swan() {
flyBehavior=new FlyNormal();
swimBehavior=new SwimNormal();
}
}
public class WildGoose extends Goose{
public WildGoose() {
flyBehavior=new FlyGood();
swimBehavior=new SwimNormal();
}
}
public class GreyGoose extends Goose{
public GreyGoose() {
flyBehavior=new FlyNormal();
swimBehavior=new SwimGood();
}
}
public class Client {
public static void main(String[] args) {
Swan swan=new Swan();
swan.flyBehavior.fly();
WildGoose wildGoose=new WildGoose();
wildGoose.swimBehavior.swim();
GreyGoose greyGoose=new GreyGoose();
greyGoose.flyBehavior.fly();
greyGoose.setFlyBehavior(new FlyGood()); //改变某个对象的行为
greyGoose.flyBehavior.fly();
}
}