小狗在不同环境条件下可能呈现出不同的状态表现,要求用接口封装小狗的状态。具体要求如下:
- 编写一个接口DogState,该接口有一个名字为void showState()的方法。
- 编写Dog类,该类中有一个DogState接口声明的变量State。另外,该类有一个show()方法,在该方法中让接口state回调showState()方法。
- 编写若干个实现DogState接口的类,负责刻画小狗的各种状态。
- 编写主类,在主类中测试小狗的各种状态。
package main;
public interface DogState {
public void showState();
}
public class Dog {
DogState state;
public void show(){
state.showState();
}
public void setState(DogState s){
state=s;
}
}
public class MeetEnemyState implements DogState{
void showState()
{
System.out.println("狗会警惕!");
}//重写showState()
}
public class MeetFriendState implements DogState{
void showState()
{
System.out.println("狗会开心!");
}//重写showState()
}
public class MeetAnotherDog implements DogState{
void showState()
{
System.out.println("狗会摇尾巴!");
}//重写showState()
}
public class CheckDogState {
public static void main(String[] args) {
Dog yellowDog=new Dog();
System.out.print("狗遇到敌人");
yellowDog.setState(new MeetEnemyState());
yellowDog.show();
System.out.print("狗遇到朋友");
yellowDog.setState(new MeetFriendState());
yellowDog.show();
System.out.print("狗遇到同伴");
yellowDog.setState(new MeetAnotherDog());
yellowDog.show();
}
}
运行结果截图: