读书人

设计方式之命令模式

发布时间: 2012-09-20 09:36:50 作者: rapoo

设计模式之命令模式
命令模式即命令发起者和命令执行者分离,从而实现解耦.举个例子,一个父亲有三个儿子,现在家里需要钱,就派他们出去赚钱;三个儿子各有所长,有的教书,有的做饭,还有个开车,就各用自己本事赚钱去.父亲只要他们去赚钱,具体怎么赚他不关心;儿子接到赚钱的命令,自会各显神通,赚回money.

// the Command interfaceinterface Command {public void earn();}// each son implements the interfaceclass 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 commanderclass 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);}}

读书人网 >软件开发

热点推荐