第一个帖子。写的不好望大家见谅。
欢迎来到未来城,在未来城里,一切都是用遥控来操控的。现在家里有个Light。其有on 和 off2个方法。(light是操控对象)。
主要部件Command,一个接口,及其实现了它的2个方法,LightOnCommand和LightOffCommand,代码:
LightOnCommand:
LightOffCommand:
下来就是遥控器啦。
代码:
然后则是客户端的调用。
给class图给大家看看,这是我第一次用软件画类图,如果有什么不妥的地方,或是错误的地方请大家见谅,也请指出来,谢谢!
[img]/upload/attachment/81482/997b0538-babd-3bab-94f1-c7c37477e49e.jpg[/img]
我所认为,读取类图比看代码更容易理解。
-----------------------------------------------------------------------
当控制对象(这里是ligght类)增加的时候,如果还有电视机,冰箱,热水器,门……这些东西增多的时候,或许我们应该在这个控制对象中加入一个新的设计模式,那边是策略模式。
欢迎来到未来城,在未来城里,一切都是用遥控来操控的。现在家里有个Light。其有on 和 off2个方法。(light是操控对象)。
package com.duduli.li.command;
public class Light {
public void on(){
System.out.println("light on!");
}
public void off(){
System.out.println("light off");
}
}
主要部件Command,一个接口,及其实现了它的2个方法,LightOnCommand和LightOffCommand,代码:
package com.duduli.li.command;
public interface Command {
public void execute();
}
LightOnCommand:
package com.duduli.li.command;
public class LightOnCommand implements Command {
private Light light;
public LightOnCommand(Light light){
this.light = light;
}
@Override
public void execute() {
light.on();
}
}
LightOffCommand:
package com.duduli.li.command;
public class LightOffCommand implements Command{
private Light light;
public LightOffCommand(Light light){
this.light = light;
}
@Override
public void execute() {
light.off();
}
}
下来就是遥控器啦。
代码:
package com.duduli.li.command;
public class Telecontrol {
Command slit;
public void setCommand(Command command){
this.slit = command;
}
public void buttonPressed(){
slit.execute();
}
}
然后则是客户端的调用。
package com.duduli.li.command;
public class Cient {
public static void main(String[] args) {
Telecontrol tc = new Telecontrol();
Light l = new Light();
LightOnCommand lon = new LightOnCommand(l);
tc.setCommand(lon);
tc.buttonPressed();
}
}
给class图给大家看看,这是我第一次用软件画类图,如果有什么不妥的地方,或是错误的地方请大家见谅,也请指出来,谢谢!
[img]/upload/attachment/81482/997b0538-babd-3bab-94f1-c7c37477e49e.jpg[/img]
我所认为,读取类图比看代码更容易理解。
-----------------------------------------------------------------------
当控制对象(这里是ligght类)增加的时候,如果还有电视机,冰箱,热水器,门……这些东西增多的时候,或许我们应该在这个控制对象中加入一个新的设计模式,那边是策略模式。