`

《Head First设计模式》阅读笔记.第六章

    博客分类:
  • Java
阅读更多
1.命令(Command)模式部分

引用
----连连看解答----
女招待->Invoker
快餐厨师->Receiver
orderUp()->execute()
订单->Command
顾客->Client
takeOrder()->setCommand
------------


----GarageDoorOpenCommand类----
public class GarageDoorOpenCommand {
    GarageDoor door;
    
    public GarageDoorOpenCommand(GarageDoor door){
        this.door = door;
    }
    
    public void execute() {
        door.up();
    }
}
------------


命令(Command)模式:将“请求”封装成对象,以便使用请求、队列或日志来参数化其它对象。命令模式也支持可撤销的操作。

*命令对象通过在一个特定接受者上绑定一组动作来封装请求。为实现这一点,命令对象将动作和接受者包进对象中。

*空对象(null object)可以用于返回无意义的对象时,它可以承担处理null的责任。有时候空对象也被视为一种设计模式。

*将命令执行之前的状态记录在命令对象中,这样就可以实现更复杂的撤销操作。

----CeilingFanLowCommand类----
public class CeilingFanLowCommand implements Command {
    private CeilingFan fan;
    private int prevSpeed;
    
    public CeilingFanLowCommand(CeilingFan fan) {
        this.fan = fan;
    }
    
    public void execute() {
        prevSpeed = fan.getSpeed();
        fan.low();
    }
    
    public void undo() {
        if (prevSpeed == CeilingFan.HIGH) {
            fan.high();
        } else if (prevSpeed == CeilingFan.MEDIUM) {
            fan.medium();
        } else if (prevSpeed == CeilingFan.LOW) {
            fan.low();
        } else if (prevSpeed == CeilingFan.OFF) {
            fan.off();
        }
    }
}
------------

----CeilingFanMediumCommand类----
public class CeilingFanMediumCommand implements Command {
    private CeilingFan fan;
    private int prevSpeed;
    
    public CeilingFanMediumCommand(CeilingFan fan) {
        this.fan = fan;
    }
    
    public void execute() {
        prevSpeed = fan.getSpeed();
        fan.medium();
    }
    
    public void undo() {
        if (prevSpeed == CeilingFan.HIGH) {
            fan.high();
        } else if (prevSpeed == CeilingFan.MEDIUM) {
            fan.medium();
        } else if (prevSpeed == CeilingFan.LOW) {
            fan.low();
        } else if (prevSpeed == CeilingFan.OFF) {
            fan.off();
        }
    }
}
------------

----CeilingFanOffCommand类----
public class CeilingFanOffCommand implements Command {
    private CeilingFan fan;
    private int prevSpeed;
    
    public CeilingFanOffCommand(CeilingFan fan) {
        this.fan = fan;
    }
    
    public void execute() {
        prevSpeed = fan.getSpeed();
        fan.off();
    }
    
    public void undo() {
        if (prevSpeed == CeilingFan.HIGH) {
            fan.high();
        } else if (prevSpeed == CeilingFan.MEDIUM) {
            fan.medium();
        } else if (prevSpeed == CeilingFan.LOW) {
            fan.low();
        } else if (prevSpeed == CeilingFan.OFF) {
            fan.off();
        }
    }
}
------------


*宏命令(Macro Command)是一个命令队列,它包含了一组实现了同一个命令接口的类。

----Sharpen Your Pencil解答----
Light light = new Light("Living Room");
TV tv = new TV("Living Room");
Stereo stereo = new Stereo("Living Room");
Hottub hottub = new Hottub();

LightOffCommand lightoff = new LightOffCommand(light);
TVOffCommand tvoff = new TVOffCommand(tv);
StereoOffCommand stereooff = new StereoOffCommand(stereo);
HottubOffCommand hottuboff = new HottubOffCommand(hottub);
------------

----undo()方法----
public void undo() {
    // 我觉得根据命令执行的顺序反向地撤销更为合理
    for(int i = commands.length() - 1; i >= 0; i--) {
        commands[i].undo();
    }
}
------------


*命令(Command)模式通过把接受者当作参数来传递,并且让所有的命令对象都实现一个命令接口的方式,实现了针对接口编程,从而在调用者和接受者之间实现了解耦。

*在调用者中用一个堆栈记录连续执行的命令,这样就可以实现每按一次按钮就执行一次撤销操作的连续撤销功能。

*命令(Command)模式将发出请求的对象和执行请求的对象解耦。

*被解耦的对象之间通过命令对象进行沟通,命令对象封装了接受者和一个或一组动作。

*宏命令是命令的一种简单延伸,执行调用多个命令。宏方法也可以支持撤销。

*在实际操作时,很常见地用“聪明”命令对象,也就是直接实现了请求,而不是将工作委托(Delegate)给接收者。

*命令可以被用来实现日志和事物系统。

2.命令(Command)模式实例
// mp3播放器
public class Mp3Player {
	private String name;

	public Mp3Player(String n) {
		this.name = n;
	}

	public void playMusic() {
		System.out.println("Music is playing.");
	}

	public void stopMusic() {
		System.out.println("Music is stopped.");
	}

	public String getName() {
		return name;
	}
}

// 收音机
public class Radio {
	private float frequency = 100;// 频率

	private String name;

	public Radio(String n) {
		this.name = n;
	}

	public void on() {
		System.out.println("Radio is on.");
	}

	public void off() {
		System.out.println("Radio is off.");
	}

	public void setFrequency(float f) {
		this.frequency = f;
		System.out.println("Frequency is set to " + f);
	}

	public float getFrequency() {
		return this.frequency;
	}

	public String getName() {
		return name;
	}
}

// 命令接口
public interface Command {
	public void execute();

	public void undo();
}

// 播放音乐命令
public class PlayMusicCommand implements Command {
	private Mp3Player player;

	public PlayMusicCommand(Mp3Player p) {
		this.player = p;
	}

	public void execute() {
		this.player.playMusic();
	}

	public void undo() {
		this.player.stopMusic();
	}
}

// 停止音乐命令
public class StopMusicCommand implements Command {
	private Mp3Player player;

	public StopMusicCommand(Mp3Player p) {
		this.player = p;
	}

	public void execute() {
		this.player.stopMusic();
	}

	public void undo() {
		this.player.playMusic();
	}
}

// 打开收音机命令
public class RadioOnCommand implements Command {
	private Radio radio;

	public RadioOnCommand(Radio p) {
		this.radio = p;
	}

	public void execute() {
		this.radio.on();
	}

	public void undo() {
		this.radio.off();
	}
}

// 关闭收音机命令
public class RadioOffCommand implements Command {
	private Radio radio;

	public RadioOffCommand(Radio p) {
		this.radio = p;
	}

	public void execute() {
		this.radio.off();
	}

	public void undo() {
		this.radio.on();
	}
}

// 频率调高命令
public class FrequencyHigherCommand implements Command {
	private Radio radio;

	private float prevFre;

	public FrequencyHigherCommand(Radio p) {
		this.radio = p;
	}

	public void execute() {
		this.prevFre = radio.getFrequency();
		radio.setFrequency(this.prevFre + 0.1f);
	}

	public void undo() {
		this.radio.setFrequency(prevFre);
	}
}

// 频率调低命令
public class FrequencylowerCommand implements Command {
	private Radio radio;

	private float prevFre;

	public FrequencylowerCommand(Radio p) {
		this.radio = p;
	}

	public void execute() {
		this.prevFre = radio.getFrequency();
		if (this.prevFre >= 0.1)
			radio.setFrequency(this.prevFre - 0.1f);
	}

	public void undo() {
		this.radio.setFrequency(prevFre);
	}
}

// 遥控器
public class RemoteControl {
	private Command[] leftCommands;

	private Command[] rightCommands;

	private Command prevCommand;

	public RemoteControl() {
		leftCommands = new Command[3];
		rightCommands = new Command[3];

		for (int i = 0; i < leftCommands.length; i++) {
			leftCommands[i] = new NoCommand();
		}
		for (int i = 0; i < rightCommands.length; i++) {
			rightCommands[i] = new NoCommand();
		}

		prevCommand = new NoCommand();
	}

	public void setCommand(int index, Command left, Command right) {
		leftCommands[index] = left;
		rightCommands[index] = right;
	}

	public void leftButtonPressed(int index) {
		System.out.println("Left button [" + index + "] is pressed.");
		leftCommands[index].execute();
		prevCommand = leftCommands[index];
	}

	public void rightButtonPressed(int index) {
		System.out.println("Right button [" + index + "] is pressed.");
		rightCommands[index].execute();
		prevCommand = rightCommands[index];
	}

	public void cancelButtonPressed() {
		System.out.println("Cancel button is pressed.");
		prevCommand.undo();
	}
}

// 空命令,处理空对象(null object)
public class NoCommand implements Command {
	public void execute() {
	}

	public void undo() {
	}
}

----命令(Command)模式测试程序----
// 测试程序
public class TestRemoteControl {
	public static void main(String[] args) {
		RemoteControl rc = new RemoteControl();

		Mp3Player player = new Mp3Player("Sony Ericsson");
		PlayMusicCommand pm = new PlayMusicCommand(player);
		StopMusicCommand sm = new StopMusicCommand(player);
		rc.setCommand(0, pm, sm);

		Radio radio = new Radio("Tecsun");
		RadioOnCommand ron = new RadioOnCommand(radio);
		RadioOffCommand roff = new RadioOffCommand(radio);
		FrequencyHigherCommand fh = new FrequencyHigherCommand(radio);
		FrequencylowerCommand fl = new FrequencylowerCommand(radio);
		rc.setCommand(1, ron, roff);
		rc.setCommand(2, fh, fl);
		
		rc.leftButtonPressed(0);
		rc.cancelButtonPressed();
		rc.leftButtonPressed(0);
		rc.rightButtonPressed(0);
		rc.cancelButtonPressed();
		
		rc.leftButtonPressed(1);
		rc.cancelButtonPressed();
		rc.leftButtonPressed(1);
		rc.rightButtonPressed(1);
		rc.cancelButtonPressed();
		
		rc.leftButtonPressed(2);
		rc.cancelButtonPressed();
		rc.leftButtonPressed(2);
		rc.rightButtonPressed(2);
		rc.cancelButtonPressed();
	}
}


引用
----测试程序运行结果----
Left button [0] is pressed.
Music is playing.
Cancel button is pressed.
Music is stopped.
Left button [0] is pressed.
Music is playing.
Right button [0] is pressed.
Music is stopped.
Cancel button is pressed.
Music is playing.
Left button [1] is pressed.
Radio is on.
Cancel button is pressed.
Radio is off.
Left button [1] is pressed.
Radio is on.
Right button [1] is pressed.
Radio is off.
Cancel button is pressed.
Radio is on.
Left button [2] is pressed.
Frequency is set to 100.1
Cancel button is pressed.
Frequency is set to 100.0
Left button [2] is pressed.
Frequency is set to 100.1
Right button [2] is pressed.
Frequency is set to 100.0
Cancel button is pressed.
Frequency is set to 100.1

------------


3.宏命令(Macro Command)实例

在以上代码基础上完成:
// 宏命令
public class MacroCommand implements Command {
	private Command[] commands;

	public MacroCommand(Command[] commands) {
		this.commands = commands;
	}

	public void execute() {
		for (int i = 0; i < commands.length; i++) {
			commands[i].execute();
		}
	}

	public void undo() {
		for (int i = commands.length - 1; i >= 0; i--) {
			commands[i].undo();
		}
	}
}

----宏命令(Macro Command)测试程序----
// 测试宏命令
public class TestMacroCommand {
	public static void main(String[] args) {
		Mp3Player player = new Mp3Player("Sony Ericsson");
		PlayMusicCommand pm = new PlayMusicCommand(player);
		StopMusicCommand sm = new StopMusicCommand(player);

		Radio radio = new Radio("Tecsun");
		RadioOnCommand ron = new RadioOnCommand(radio);
		RadioOffCommand roff = new RadioOffCommand(radio);
		FrequencyHigherCommand fh = new FrequencyHigherCommand(radio);
		FrequencylowerCommand fl = new FrequencylowerCommand(radio);
		FrequencyHigherCommand fh2 = new FrequencyHigherCommand(radio);
		FrequencylowerCommand fl2 = new FrequencylowerCommand(radio);

		Command[] commands = new Command[] { pm, sm, ron, fh, fh2, fl, fl2, roff };
		MacroCommand mc = new MacroCommand(commands);

		RemoteControl rc = new RemoteControl();
		rc.setCommand(0, mc, mc);
		rc.leftButtonPressed(0);
		rc.cancelButtonPressed();
	}
}


引用
----测试程序运行结果----
Left button [0] is pressed.
Music is playing.
Music is stopped.
Radio is on.
Frequency is set to 100.1
Frequency is set to 100.2
Frequency is set to 100.1
Frequency is set to 100.0
Radio is off.
Cancel button is pressed.
Radio is on.
Frequency is set to 100.1
Frequency is set to 100.2
Frequency is set to 100.1
Frequency is set to 100.0
Radio is off.
Music is playing.
Music is stopped.

--------


4.聪明命令(Smart Command)实例

在以上代码基础上完成:
// 聪明(Smart)命令实例
public class PrintLogCommand implements Command {
	public void execute() {
		// 自己实现,而不是委托其它类
		System.out.println("Log at " + new Date());
	}

	public void undo() {
		// 命令可以支持撤销,也可以不支持
	}
}

----聪明命令(Smart Command)测试程序----
// 测试聪明命令
public class TestSmartCommand {
	public static void main(String[] args) {
		PrintLogCommand pl = new PrintLogCommand();
		RemoteControl rc = new RemoteControl();
		rc.setCommand(0, pl, pl);
		rc.leftButtonPressed(0);
	}
}


引用
----测试程序运行结果----
Left button [0] is pressed.
Log at Tue Jan 19 14:44:02 CST 2010

------------


--END--
3
0
分享到:
评论

相关推荐

    笔记_HeadFirst设计模式.pdf

    笔记_HeadFirst设计模式

    Head.First 设计模式学习笔记.pdf

    ### Head.First 设计模式学习笔记知识点总结 #### 一、设计模式概述 设计模式是一种用于解决软件设计中常见问题的标准化方法。通过采用设计模式,开发者可以提高代码的复用性、灵活性和可维护性。《Head First 设计...

    HeadFirst设计模式学习笔记

    《HeadFirst设计模式学习笔记》是一份详尽的资料,旨在帮助读者深入理解并掌握设计模式这一编程领域的核心概念。设计模式是软件工程中的一种最佳实践,它在解决常见问题时提供了一种标准的解决方案,使得代码更易于...

    HeadFirst 设计模式学习笔记1--策略模式Demo

    《HeadFirst设计模式学习笔记1--策略模式Demo》 在软件工程中,设计模式是一种解决常见问题的标准方案,它提供了一种在特定情况下组织代码的模板。策略模式是设计模式中的一种行为模式,它允许在运行时选择算法或...

    HeadFirst 设计模式学习笔记3--装饰模式 Demo

    在“HeadFirst 设计模式学习笔记3--装饰模式 Demo”中,作者通过实例讲解了装饰模式的基本概念、结构和应用场景。这篇文章可能是从CSDN博客平台上的一个链接访问的,遗憾的是,由于我们当前无法直接访问该链接,所以...

    HeadFirst设计模式读书笔记

    HeadFirst设计模式 读书 笔记

    HeadFirst 设计模式学习笔记2--观察者模式 demo

    总的来说,HeadFirst设计模式的学习笔记2关于观察者模式的演示,旨在帮助开发者理解如何使用观察者模式来构建可扩展的系统。通过实际的代码示例,我们可以更深入地掌握这一模式,并将其应用到日常开发中,提升代码的...

    读书笔记:设计模式学习笔记和代码。《图解设计模式》《Head First 设计模式》.zip

    读书笔记:设计模式学习笔记和代码。《图解设计模式》《Head First 设计模式》

    Head First 设计模式 扫描版

    《Head First 设计模式》是软件开发领域内一本广受欢迎的书籍,由Eric Freeman、Elisabeth Robson、Bert Bates和Kathy Sierra四位作者共同撰写。这本书以其独特的视觉风格和易于理解的教学方法,深入浅出地介绍了...

    Head First设计模式读书笔记-DesignPatterns.zip

    《Head First设计模式》是一本深受开发者喜爱的设计模式学习书籍,它以易懂且生动的方式介绍了23种经典设计模式。这些模式是软件工程中经过实践验证的最佳实践,旨在提高代码的可重用性、可读性和可维护性。下面,...

    HeadFirst设计模式笔记

    《HeadFirst设计模式笔记》是深入理解软件设计思想的一份宝贵资料,主要涵盖了设计模式这一核心编程概念。设计模式是经过实践验证的解决方案模板,用于解决在软件开发中经常遇到的问题,尤其在面向对象设计中。这篇...

    Head First 设计模式学习笔记(十四)模式的组合使用

    在《Head First 设计模式学习笔记(十四)模式的组合使用》中,作者探讨了如何在实际编程中灵活地组合多种设计模式以解决复杂问题。这篇文章可能是基于《Head First 设计模式》这本书的一个章节,该书是设计模式领域...

    《Head First设计模式》读书笔记 -- (第一章)策略模式

    《Head First设计模式》是软件开发领域的一本经典著作,其深入浅出地介绍了23种设计模式。第一章主要讲解的是策略模式,这是一种行为设计模式,它使你能在运行时改变对象的行为。策略模式的核心思想是定义一系列算法...

    基于Java语言的《Head First 设计模式》学习笔记及实战练习源码

    本项目为《Head First 设计模式》的Java语言学习笔记与实战练习源码集合,包含104个文件,主要包括88个Java源文件、12个Markdown文档、3个XML配置文件及少量其他辅助文件。内容涵盖设计模式的学习笔记以及相应的代码...

    Head First Design Pattern 学习笔记

    著名的《Head First Design ...由于书本过长,整理出笔记帮助回想起设计模式。文件是docx格式,只能由OFFICE Word 2007之后的版本打开,内附Visio类图文件。本文由个人整理摘录,部分内容来自书本,仅供学习使用。

    head first 设计模式

    根据提供的信息,“Head First设计模式”是一本广受好评的设计模式书籍。虽然具体的章节内容没有给出,但从描述中得知本书的第22页至39页涵盖了重要的设计模式概念,因此我们将围绕这些页面可能涉及的设计模式进行...

    Head First Servlets & JSP 学习笔记

    以上只是《Head First Servlets & JSP》一书中的部分核心知识点,实际内容还包括过滤器、监听器、MVC设计模式、JSTL等更广泛的主题,旨在帮助读者全面理解和掌握Servlet和JSP技术。通过深入学习,开发者能够构建高效...

    head_first_servlet&jsp学习笔记

    【Servlet&JSP基础知识】 ...以上是`head_first_servlet&jsp`学习笔记的主要知识点,涵盖了Servlet和JSP的基础、Web应用架构、MVC模式、会话管理和JSP编程等多个方面,为深入理解和实践Servlet与JSP开发奠定了基础。

Global site tag (gtag.js) - Google Analytics