面向对象-duck
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了面向对象-duck相关的知识,希望对你有一定的参考价值。
package oo;
public interface Duck {
public void fly();
public void quack();
}
package oo;
public class MallardDuck implements Duck {
public void fly()
{
System.out.println("I‘m flying");
}
public void quack()
{
System.out.println("Quack");
}
}
package oo;
public interface Turkey {
public void gobble();
public void fly();
}
package oo;
public class WildTurkey implements Turkey{
public void gobble()
{
System.out.println("Gobble gobble");
}
public void fly()
{
System.out.println("I‘m flying a short distance");
}
}
package oo;
import java.util.Random;
public class DuckAdapter implements Turkey{
Duck duck;
Random rand;
public DuckAdapter(Duck duck)
{
this.duck=duck;
rand=new Random();
}
public void gobble()
{
duck.quack();
}
public void fly()
{
if (rand.nextInt(5)==0)
{
duck.fly();
}
}
}
package oo;
public class TurkeyAdapter implements Duck{
Turkey turkey;
public TurkeyAdapter(Turkey turkey)
{
this.turkey=turkey;
}
public void quack()
{
turkey.gobble();
}
public void fly()
{
for (int i=0;i<5;i++)
{
turkey.fly();
}
}
}
package oo;
public class DuckTestDrive {
public static void main(String[]args)
{
MallardDuck duck=new MallardDuck();
WildTurkey turkey=new WildTurkey();
Duck turkeyAdapter=new TurkeyAdapter(turkey);
System.out.println("the turkey says..");
turkey.gobble();
turkey.fly();
System.out.println("the duck says..");
test(duck);
System.out.println("the turkeyadapter says..");
test(turkeyAdapter);
}
static void test(Duck duck)
{
duck.quack();
duck.fly();
}
}
package oo;
public class TurkeyTestDrive {
public static void main(String []args)
{
MallardDuck duck=new MallardDuck();
Turkey duckAdapter=new DuckAdapter(duck);
for(int i=0;i<10;i++)
{
System.out.println("the duckadapter says..");
duckAdapter.gobble();
duckAdapter.fly();
}
}
}
以上是关于面向对象-duck的主要内容,如果未能解决你的问题,请参考以下文章