命令模式---电视机遥控器

电视机是请求的接收者,遥控器是请求的发送者,遥控器上有一些按钮,不同的按钮对应电视机的不同操作。抽象命令角色由一个命令接口来扮演,有三个具体的命令类实现了抽象命令接口,这三个具体命令类分别代表三种操作:打开电视机、关闭电视机和切换频道。显然,电视机遥控器就是一个典型的命令模式应用实例。

 

Command.java

package TVCmd;

public abstract class Command {
	public abstract void execute();
}

Televlsion.java

package TVCmd;

public class Televlsion {
	public void open() {
		System.err.println("打开电视机。。。。");
	}
	public void close() {
		System.err.println("关闭电视机。。。。");
	}
	public void change() {
		System.err.println("换台。。。。");
	}
	
}

TVOpenCommand.java

package TVCmd;

public class TVOpenCommand extends Command {
	private Televlsion tv=new Televlsion();
	
	@Override
	public void execute() {
		// TODO Auto-generated method stub
		tv.open();
	}

}

TVCloseCommand.java

package TVCmd;

public class TVCloseCommand extends Command {
	private Televlsion tv=new Televlsion();
	
	@Override
	public void execute() {
		// TODO Auto-generated method stub
		tv.close();
	}

}

TVChangeCommand.java

package TVCmd;

public class TVChangeCommand extends Command {
	private Televlsion tv=new Televlsion();
	

	@Override
	public void execute() {
		// TODO Auto-generated method stub
		tv.change();
	}

}

Controller.java

package TVCmd;

public class Controller {
	private Command command; 
	public Controller(Command command) {
		this.command=command;
	}
	public void function() {
		command.execute();
	}
	
}

Client.java

package TVCmd;

public class Client {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		Command cmd,cmd2,cmd3;
		
		//打开电视机
		cmd=new TVOpenCommand();
		Controller c1=new Controller(cmd);
		c1.function();
		
		//关闭电视机
		cmd2=new TVCloseCommand();
		Controller c2=new Controller(cmd2);
		c2.function();
		
		//换台
		cmd3=new TVChangeCommand();
		Controller c3=new Controller(cmd3);
		c3.function();
		
	}

}

运行截图:

命令模式---电视机遥控器_第1张图片

 

你可能感兴趣的:(设计模式)