package adapter;
public abstract class Duck {
FlyBehavior flyBehavior;
QuackBehavior quackBehavior;
public Duck()
{
}
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!");
}
}
package adapter;
public interface QuackBehavior {
public void quack();
}
package adapter;
public interface FlyBehavior {
public void fly();
}
package adapter;
public class MallardDuck extends Duck{
public MallardDuck()
{
quackBehavior=new Quack();
flyBehavior=new FlyWithWings();
}
public void display()
{
System.out.println("i‘m a real Mallard duck");
}
}
package adapter;
public class ModelDuck extends Duck{
public ModelDuck()
{
flyBehavior=new FlyNoWay();
quackBehavior=new Quack();
}
public void display()
{
System.out.println("I‘m a model duck");
}
}
package adapter;
public class RubberDuck extends Duck {
public RubberDuck() {
flyBehavior = new FlyNoWay();
quackBehavior = new Squeak();
}
public void display() {
System.out.println("I‘m a rubber duckie");
}
}
package adapter;
public class DecoyDuck extends Duck{
public DecoyDuck()
{
setFlyBehavior(new FlyNoWay());
setQuackBehavior(new MuteQuack());
}
public void display()
{
System.out.println("i‘m a duck decoy");
}
}
package adapter;
public class MuteQuack implements QuackBehavior {
public void quack() {
System.out.println("<< Silence >>");
}
}
package adapter;
public class FakeQuack implements QuackBehavior{
public void quack()
{
System.out.println("Qwak");
}
}
package adapter;
public class FlyNoWay implements FlyBehavior{
public void fly()
{
System.out.println("i can‘t fly");
}
}
package adapter;
public class FlyWithWings implements FlyBehavior{
public void fly()
{
System.out.println("i‘m flying");
}
}
package adapter;
public class FlyRocketPowered implements FlyBehavior{
public void fly()
{
System.out.println("i‘m flying with a rocket");
}
}
package adapter;
public class MiniDuckSimulator {
public static void main(String[] args)
{
MallardDuck mallard=new MallardDuck();
RubberDuck rubberDuckie=new RubberDuck();
DecoyDuck decoy=new DecoyDuck();
ModelDuck model=new ModelDuck();
mallard.performQuack();
rubberDuckie.performQuack();
decoy.performQuack();
model.performFly();
model.setFlyBehavior(new FlyRocketPowered());
model.performFly();
}
}
package adapter;
public class MiniDuckSimulator1 {public static void main(String []args){ Duck mallard=new MallardDuck(); mallard.performQuack();
mallard.performFly();
Duck model=new ModelDuck();
model.performFly();
model.setFlyBehavior(new FlyRocketPowered());
model.performFly();
}
}