public abstract class Duck {
public Duck() {
}
/**
* 显示鸭子信息
*/
public abstract void display();
public void quack(){
System.out.println("鸭子嘎嘎叫");
}
public void swim(){
System.out.println("鸭子游泳");
}
public void fly(){
System.out.println("鸭子飞行");
}
}
public class PekingDuck extends Duck {
@Override
public void display() {
System.out.println("北京鸭");
}
/**
* 因为北京鸭不能飞 因此需要重写fly
*/
@Override
public void fly() {
System.out.println("北京鸭不能飞");
}
}
public class ToyDuck extends Duck {
@Override
public void display() {
System.out.println("玩具鸭");
}
/**
* 需要重写父类所有方法
*/
@Override
public void quack(){
System.out.println("玩具不能叫");
}
@Override
public void swim(){
System.out.println("玩具鸭子不游泳");
}
@Override
public void fly(){
System.out.println("玩具鸭子不飞行");
}
}
public class WildDuck extends Duck {
@Override
public void display() {
System.out.println("野鸭");
}
}
public abstract class Duck {
/**
* 聚合,策略接口
*/
FlyBehavior flyBehavior;
public Duck() {
}
/**
* 显示鸭子信息
*/
public abstract void display();
public void quack(){
System.out.println("鸭子嘎嘎叫");
}
public void swim(){
System.out.println("鸭子游泳");
}
public void fly(){
if (flyBehavior != null){
flyBehavior.fly();
}
}
public void setFlyBehavior(FlyBehavior flyBehavior) {
this.flyBehavior = flyBehavior;
}
}
public class BadFlyBehavior implements FlyBehavior {
@Override
public void fly() {
System.out.println("飞的一般");
}
}
public class GoodFlyBehavior implements FlyBehavior{
@Override
public void fly() {
System.out.println("飞翔牛逼");
}
}
public class NoFlyBehavior implements FlyBehavior {
@Override
public void fly() {
System.out.println("不会飞");
}
}
public class PekingDuck extends Duck {
@Override
public void display() {
System.out.println("北京鸭");
}
public PekingDuck() {
flyBehavior = new BadFlyBehavior();
}
}
public class ToyDuck extends Duck {
@Override
public void display() {
System.out.println("玩具鸭");
}
/**
* 需要重写父类所有方法
*/
@Override
public void quack(){
System.out.println("玩具不能叫");
}
@Override
public void swim(){
System.out.println("玩具鸭子不游泳");
}
public ToyDuck() {
flyBehavior = new NoFlyBehavior();
}
}
public class WildDuck extends Duck {
@Override
public void display() {
System.out.println("野鸭");
}
/**
* 传入FlyBehavor
*/
public WildDuck() {
flyBehavior = new GoodFlyBehavior();
}
}
public class Client {
public static void main(String[] args) {
WildDuck wildDuck = new WildDuck();
wildDuck.fly();
ToyDuck toyDuck = new ToyDuck();
toyDuck.fly();
PekingDuck pekingDuck = new PekingDuck();
pekingDuck.fly();
//动态改变某个对象的行为
pekingDuck.setFlyBehavior(new NoFlyBehavior());
pekingDuck.fly();
}
}
文章目录编写鸭子项目传统方案解决鸭子问题的分析和代码实现代码传统的方式实现的问题分析和解决方案策略者模式基本介绍原理类图策略者模式解决鸭子问题思路分析代码策略者模式在JDK-Arrays应用的源码分析策略者模式的注意事项和细节编写鸭子项目传统方案解决鸭子问题的分析和代码实现代码public abstract class Duck { public Duck() { ...