/***
* @author shaofan
* @Description 策略模式解决鸭子问题
*/
public class DuckInfo {
public static void main(String[] args) {
Duck wildDuck =new WildDuck();
Duck toyDuck = new ToyDuck();
wildDuck.fly();
toyDuck.fly();
}
}
abstract class Duck{
Flyable flyable;
public Duck(Flyable flyable){
this.flyable = flyable;
}
public void fly(){
flyable.fly();
}
}
class WildDuck extends Duck{
public WildDuck() {
super(new GoodFlyable());
}
}
class ToyDuck extends Duck{
public ToyDuck() {
super(new NoFlyable());
}
}
interface Flyable{
void fly();
}
class NoFlyable implements Flyable{
@Override
public void fly() {
System.out.println("不能飞");
}
}
class GoodFlyable implements Flyable{
@Override
public void fly() {
System.out.println("擅长飞");
}
}
class BadFlyable implements Flyable{
@Override
public void fly() {
System.out.println("不擅长飞");
}
}
如Arrays中的sort方法,针对传入的Comparator,来确定排序的策略,如果没有传入则为默认的升序,
Comparator就是策略对象,排序行为和Arrays分离开了