新建一个鸭子抽象类,共有的功能在类中进行实现。会有差异性的单独做成接口。
public abstract class Duck {
//为行为借口类型什么两个应用变量,所有鸭子之类都继承它们
FlyBehavior flyBehavior;
QuackBehavior quackBehavior;
public Duck() {
}
//这两个功能可以再运行过程中改变鸭子的行为,通过赋予不同的FlyBehavior实现类即可
public void setFlyBehavior(FlyBehavior fb) {
flyBehavior = fb;
}
public void setQuackBehavior(QuackBehavior qb) {
quackBehavior = qb;
}
abstract void display();
public void performFly() {
//委托给行为类来实现
flyBehavior.fly();
}
public void performQuack() {
//委托给行为类来实现
quackBehavior.quack();
}
public void swim() {
System.out.println("All ducks float, even decoys!");
}
}
实现类绿头鸭
public class MallardDuck extends Duck {
public MallardDuck() {
//绿头鸭使用Quack类处理呱呱叫,所以当performQuack()被调用时,叫的职责被委托给了Quack对象。实际处理
quackBehavior = new Quack();
flyBehavior = new FlyWithWings();
//使用FlyWithWings作为FlyBehavior类型的实现,利用多态。
//同一个接口使用不同的实例而自信不同操作
}
@Override
public void display() {
System.out.println("I'm a real Mallard duck");
}
}
public interface FlyBehavior {
public void fly();
}
public class FlyWithWings implements FlyBehavior {
@Override
public void fly() {
System.out.println("I'm flying!!");
}
}
public class FlyNoWay implements FlyBehavior {
@Override
public void fly() {
System.out.println("I can't fly");
}
}
public interface QuackBehavior {
public void quack();
}
两种叫的行为
public class Quack implements QuackBehavior {
@Override
public void quack() {
System.out.println("Quack");
}
}
public class MuteQuack implements QuackBehavior {
@Override
public void quack() {
System.out.println("<< Silence >>");
}
}
测试类
public class MiniDuckSimulator {
public static void main(String[] args) {
MallardDuck mallard = new MallardDuck();
FlyBehavior cantFly = () -> System.out.println("I can't fly");
QuackBehavior squeak = () -> System.out.println("Squeak");
RubberDuck rubberDuckie = new RubberDuck(cantFly, squeak);
DecoyDuck decoy = new DecoyDuck();
Duck model = new ModelDuck();
mallard.performQuack();
rubberDuckie.performQuack();
decoy.performQuack();
model.performFly();
model.setFlyBehavior(new FlyRocketPowered());
model.performFly();
}
}