模板方法模式lua实现
2013-11-08 23:45
281 查看
--模板方法模式是通过把不变行为搬移到基类,去除之类中的重复代码来体现它的优势。 --下面以考试试卷为例,试题都是一样的,但是答案可能不一样 TestPaper = {} function TestPaper:new(o) o = o or {} setmetatable(o,self) self.__index = self return o; end function TestPaper:TestQuestion1() print("孙悟空的师弟是谁?") print("A 猪七戒 B 猪八戒 C 猪九戒") print("答案是:"..self:Answer1()) end function TestPaper:Answer1() return "" end function TestPaper:TestQuestion2() print("猪八戒的师弟是谁?") print("A 沙和尚 B 沙道士 C 沙井盖") print("答案是:"..self:Answer2()) end function TestPaper:Answer2() return "" end function TestPaper:TestQuestion3() print("沙和尚的大师兄是谁?") print("A 孙中山 B 孙权 C 孙悟空") print("答案是:"..self:Answer3()) end function TestPaper:Answer3() return "" end --小组A的试卷 GroupATestPaper = TestPaper:new() function GroupATestPaper:Answer1() return "B" end function GroupATestPaper:Answer2() return "C" end function GroupATestPaper:Answer3() return "A" end --小组B的试卷 GroupBTestPaper = TestPaper:new() function GroupBTestPaper:Answer1() return "A" end function GroupBTestPaper:Answer2() return "B" end function GroupBTestPaper:Answer3() return "C" end --小明是小组A的一员 print("********小明的试卷*********") XiaoMingTestPaper = GroupATestPaper:new() XiaoMingTestPaper:TestQuestion1() XiaoMingTestPaper:TestQuestion2() XiaoMingTestPaper:TestQuestion3() --小红是小组B的一员 print("********小红的试卷*********") XiaoHongTestPaper = GroupBTestPaper:new() XiaoHongTestPaper:TestQuestion1() XiaoHongTestPaper:TestQuestion2() XiaoHongTestPaper:TestQuestion3()
输出结果是:
********小明的试卷*********
孙悟空的师弟是谁?
A 猪七戒 B 猪八戒 C 猪九戒
答案是:B
猪八戒的师弟是谁?
A 沙和尚 B 沙道士 C 沙井盖
答案是:C
沙和尚的大师兄是谁?
A 孙中山 B 孙权 C 孙悟空
答案是:A
********小红的试卷*********
孙悟空的师弟是谁?
A 猪七戒 B 猪八戒 C 猪九戒
答案是:A
猪八戒的师弟是谁?
A 沙和尚 B 沙道士 C 沙井盖
答案是:B
沙和尚的大师兄是谁?
A 孙中山 B 孙权 C 孙悟空
答案是:C
相关文章推荐
- C++模板实现的通用工厂方法模式
- 从Spring HibernateTemplate模板方法设计模式的实现谈起
- 模板实现的通用工厂方法模式
- 设计模式C++实现(5)——原型模式、模板方法模式
- 大话设计模式--模板方法模式 TemplateMethod -- C++ 实现
- php实现设计模式之 模板方法模式
- java学习之旅50--面向对象_23_回调的实现_模板方法模式
- Java模板方法模式中的HookMethod实现
- 【JS】星级评分原理和实现(第4章 模板方法模式 - 下 )
- 设计模式C++实现(5)——原型模式、模板方法模式
- 从Spring HibernateTemplate模板方法设计模式的实现谈起
- Groovy探索之闭包 七 使用闭包来实现模板方法模式
- C++高效实现模板方法模式
- 【JS】星级评分原理和实现(第4章 模板方法模式 - 中 )
- 设计模式C++实现(5)——原型模式、模板方法模式
- Java 实现模板方法(TemplateMethod)模式
- 从Spring HibernateTemplate模板方法设计模式的实现谈起
- 设计模式C++实现(5)——原型模式、模板方法模式
- 大话设计模式C++实现-第10章-模板方法模式
- c++ 实现模板方法模式