多彩的音乐
Dog 类有一个 getFood 方法,它接受一个 Person 类型的参数.根据传入的 Person 对象的类型,
Dog 类会调用不同的方法来模拟狗的反应.在 DogReactionSimulation 类的 main 方法中,
创建了一个 Dog 对象和三种类型的 Person,然后模拟了每种人喂狗的场景,并观察狗的反应.
abstract class Person {
abstract void feedDog(Dog dog);
}
class Owner extends Person {
@Override
void feedDog(Dog dog) {
dog.getFood(this);
}
}
class FamilyMember extends Person {
@Override
void feedDog(Dog dog) {
dog.getFood(this);
}
}
class Stranger extends Person {
@Override
void feedDog(Dog dog) {
dog.getFood(this);
}
}
class Dog {
void getFood(Person person) {
if (person instanceof Owner) {
happyJump();
} else if (person instanceof FamilyMember) {
eatNormally();
} else if (person instanceof Stranger) {
beCautiousAndBark();
}
}
private void happyJump(){
System.out.println("狗非常开心,欢快地跳跃.");
}
private void eatNormally(){
System.out.println("狗很平静地吃东西.");
}
private void beCautiousAndBark(){
System.out.println("狗很警惕,并发出叫声.");
}
}
public class DogReactionSimulation {
public static void main(String[] args) {
Dog dog = new Dog();
Owner owner = new Owner();
FamilyMember familyMember = new FamilyMember();
Stranger stranger = new Stranger();
System.out.println("主人喂狗:");
owner.feedDog(dog);
System.out.println("\n家人喂狗:");
familyMember.feedDog(dog);
System.out.println("\n陌生人喂狗:");
stranger.feedDog(dog);
}
}