import java.io.*;
class Light
{
public void turnLight(int degree){
System.out.println("电灯的亮度为:" + degree);
if(degree==0)
System.out.println("关闭电灯");
else
System.out.println("将电灯调到最大亮度");
}
}
class TV
{
public void setChannel(int channel)
{
System.out.println("电视选择的频道为:" + channel);
if(channel==0)
System.out.println("关闭电视机");
else
System.out.println("将电视机调到" + channel + "频道。");
}
}
interface Command
{
void on();
void off();
}
class RemoteController
{
protected Command []commands=new Command[4];
public void onPressButton(int button)
{
if(button % 2 == 0)commands[button].on();
else commands[button].off();
}
public void setCommand(int button,Command command)
{
commands[button]=command;
}
}
class LightCommand implements Command
{
protected Light light;
public void on()
{
light.turnLight(100);
}
public void off()
{
light.turnLight(0);
}
public LightCommand(Light light)
{
this.light=light;
}
}
class TVCommand implements Command
{
protected TV tv;
protected int channel;
public void on()
{
tv.setChannel(channel);
}
public void off()
{
tv.setChannel(0);
}
public TVCommand(TV tv,int channel)
{
this.tv=tv;
this.channel=channel;
}
}
public class test_interface
{
public static void main(String[] args)
{
Light light=new Light();
TV tv=new TV();
int channel=1;
LightCommand lightCommand=new LightCommand(light);
RemoteController remoteController=new RemoteController();
remoteController.setCommand(0,lightCommand);
remoteController.setCommand(0,lightCommand);
remoteController.onPressButton(0);
System.out.println("请输入你要选择的电视频道:");
try
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String string=new String();
string=br.readLine();
try
{
channel=Integer.parseInt(string);
}
catch (NumberFormatException e)
{
System.out.println("输入错误,请重新输入数据。");
}
}
catch (IOException e)
{
System.out.println(e);
}
TVCommand tvCommand=new TVCommand(tv,channel);
remoteController.setCommand(2,tvCommand);
remoteController.onPressButton(2);
remoteController.setCommand(3,tvCommand);
remoteController.onPressButton(3);
remoteController.setCommand(1,lightCommand);
remoteController.onPressButton(1);
}
} |
|