首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件开发 >

设计方式之命令模式

2012-09-20 
设计模式之命令模式命令模式即命令发起者和命令执行者分离,从而实现解耦.举个例子,一个父亲有三个儿子,现

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

热点排行