Java面向对象学习:遥控器

已知某企业欲开发一家用电器遥控系统,即用户使用一个遥控器即可控制某些家用电器的开与关。遥控器如下图(a)所示。该遥控器共有4今按钮,编号分别是0至3,按钮0和2能够遥控打开电器1和电器2,按钮1和3则能遥控关闭电器1和电器2。由于遥控系统需要支持形式多样的电器,因此,该系统的设计要求具有较高的扩展性。现假设需要控制客厅电视和卧室电灯,对该遥控系统进行设计所得类图如下图(b)所示。
在这里插入图片描述
图(b)中,类RomoteController的方法onPrcssButton(int button)表示当遥控器按键按下时调用的方法,参数为按键的编号;command接口中on和off方法分别用于控制电器的开与关;Light中turnLight(int degree)方法用于调整电灯灯光的强弱,参数 degree值为0时表示关灯,值为100时表示开灯并且将灯光亮度调整到最大;TV中 sctChannel(int channel)方法表示设置电视播放的频道,参数channel值为0时表示关闭电视,为1时表示开机并将频道切换为第1频道。
【JAVA代码】
Command接口类:

interface Command {
    void on();
	void off();
}

Light 类:

class Light {
	public void turnLight(int degree)
	{
		if(degree==0)
			System.out.println("关灯!");
		if(degree==100)
			System.out.println("开灯,且此时灯光亮度最大。");
	}
}

TV类:

class TV {
	public void setChannel(int channel){
		if(channel==0)
			System.out.println("关闭电视!");
		if(channel==1)
			System.out.println("打开电视,此时频道为1");
	}
}

LightCommand类:

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;
	}
}

TVCommand类:

class TVCommand implements Command{
	protected TV tv;
	protected int channel;
	public void on()
	{
		tv.setChannel(1);
	}
	public void off()
	{
		tv.setChannel(0);
	}
	public TVCommand(TV tv,int channel)
	{
		this.tv=tv;
		this.channel=channel;
	}
}

RemoteController类:

class RemoteController {
	protected Command[] commands=new Command[4];
	public void onPressButton(int button){
		if(button % 2 == 0)
		{	
			System.out.println("开");
			commands[button].on();
		}
		else 
			{
			System.out.println("关");
			commands[button].off() ;
			}
		
	}
	public void setCommand(int button,Command command){
		commands[button]=command;
		
    }
}

Test测试类:

import java.util.Scanner;

public class Test {
	public static void main(String [] args)
	{
		System.out.println("-------遥控器-------");
		System.out.println("             开"+"   关");
		System.out.println("电灯        "+'0'+"  "+'1');
		System.out.println("电视        "+'2'+"  "+'3');
		@SuppressWarnings("resource")
		Scanner s=new Scanner(System.in);
		int x=s.nextInt();
		LightCommand lightCommand=new LightCommand(new Light());
		TVCommand tvCommand=new TVCommand(new TV(),x);
		RemoteController remoteController=new RemoteController();
		if(x<=1)
		{
			remoteController.setCommand(x,lightCommand);
		}else {
			remoteController.setCommand(x, tvCommand);
		}
		remoteController.onPressButton(x);
	}
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值