duck游戏
//鸭子抽象类
public abstract class duck1 {
public duck1() {
}
FlyBehaviro myFlyBehavior;
QuackBehavior myQuackBehavior;
public void fly() {
myFlyBehavior.fly();
}
public void quack() {
myQuackBehavior.QuackBehavior();
}
public abstract void display();
}
//定义飞行接口
interface FlyBehaviro {
public void fly();
}
//定义叫声接口
interface QuackBehavior {
public void QuackBehavior();
}
//飞行类
class flyNoWay implements FlyBehaviro {
@Override
public void fly() {
System.out.println(" i can not fly");
}
}
class canfly implements FlyBehaviro {
@Override
public void fly() {
System.out.println("i can fly");
}
}
//叫声类
class waquack implements QuackBehavior {
@Override
public void QuackBehavior() {
System.out.println("wawa");
}
}
class noquack implements QuackBehavior {
@Override
public void QuackBehavior() {
System.out.println("......");
}
}
class guquack implements QuackBehavior {
@Override
public void QuackBehavior() {
System.out.println("guagua");
}
}
//绿鸭
class greenduck extends duck1 {
public greenduck() {
myFlyBehavior = new canfly();
myQuackBehavior = new guquack();
}
@Override
public void display() {
System.out.println("i am greenduck");
}
}
//塑料鸭子
class plasticduck extends duck1 {
public plasticduck() {
myFlyBehavior = new flyNoWay();
myQuackBehavior = new noquack();
}
@Override
public void display() {
System.out.println("no color duck");
}
}
这里定义一个鸭子类
public class duck {
public static void main(String[] args) {
// 绿鸭
duck1 mall = new greenduck();
mall.display();
mall.fly();
mall.quack();
// 塑料鸭子
duck1 pla = new plasticduck();
pla.display();
pla.fly();
pla.quack();
}
}
运行结果:
i
am greenduck
i can fly
guagua
no color duck
i can not fly
…