命令模式即命令发起者和命令执行者分离,从而实现解耦.举个例子,一个父亲有三个儿子,现在家里需要钱,就派他们出去赚钱;三个儿子各有所长,有的教书,有的做饭,还有个开车,就各用自己本事赚钱去.父亲只要他们去赚钱,具体怎么赚他不关心;儿子接到赚钱的命令,自会各显神通,赚回money.
// the Command interface
interface Command {
public void earn();
}
// each son implements the interface
class Teacher implements Command {
public void earn() {
System.out.println("teach to earn");
}
}
class Driver implements Command {
public void earn() {
System.out.println("drive to earn");
}
}
class Cooker implements Command {
public void earn() {
System.out.println("cook to earn");
}
}
//father as the commander
class Father {
public void go(Command son){
son.earn();
}
}
public class Test{
public void main(String[] args){
Father father = new Father();
Teacher teacher = new Teacher();
Driver driver = new Driver();
Cooker cooker = new Cooker();
father.go(teacher);
father.go(driver);
father.go(cooker);
}
}