小狗在不同环境条件下可能呈现不同的状态表现,要求用接口封装小狗的状态。
代码如下:
interface DogState{public void showState();
}class SoftlyState implements DogState {public void showState(){System.out.println("听主人的命令!");}
}class MeetEnemyState implements DogState {public void showState(){System.out.println("上去咬一口!");}
}class MeetFriendState implements DogState {public void showState(){System.out.println("晃动尾巴,以示友好!");}
}class MeetAnotherDog implements DogState {public void showState(){System.out.println("hello!");}
}class Dog{DogState state;public void show(){state.showState();}public void setState(DogState s){state=s;}
}public class CheckDogState{public static void main(String[] args) {Dog yellowDog=new Dog();System.out.println("狗在主人面前:");yellowDog.setState(new SoftlyState());yellowDog.show();System.out.println("狗遇到敌人:");yellowDog.setState(new MeetEnemyState());yellowDog.show();System.out.println("狗遇到朋友:");yellowDog.setState(new MeetFriendState());yellowDog.show();System.out.println("狗遇到同伴:");yellowDog.setState(new MeetAnotherDog());yellowDog.show();}
}