大话设计模式(Python版)--模板方法模式
2016-10-31 08:14
351 查看
重复=易错+难改
提炼代码
模板方法模式:
#!/usr/bin/env python class TestPaperA: def TestQuestion1(self): print('TestQuestion1') print('Answer: b') def TestQuestion2(self): print('TestQuestion2') print('Answer: a') def TestQuestion3(self): print('TestQuestion3') print('Answer: c') class TestPaperB: def TestQuestion1(self): print('TestQuestion1') print('Answer: d') def TestQuestion2(self): print('TestQuestion2') print('Answer: b') def TestQuestion3(self): print('TestQuestion3') print('Answer: a') def main(): print("Student A's Test paper") studentA = TestPaperA() studentA.TestQuestion1() studentA.TestQuestion2() studentA.TestQuestion3() print("Student B's Test paper") studentB = TestPaperB() studentB.TestQuestion1() studentB.TestQuestion2() studentB.TestQuestion3() if __name__ == '__main__': main()
提炼代码
#!/usr/bin/env python from abc import ABCMeta,abstractmethod class TestPaper: __metaclass__ = ABCMeta def TestQuestion1(self): print('TestQuestion1') print('Answer:',self._Answer1()) @abstractmethod def _Answer1(self): pass class TestPaperA(TestPaper): def _Answer1(self): return 'b' class TestPaperB(TestPaper): def _Answer1(self): return 'c' def main(): print("Student A's Test paper") studentA = TestPaperA() studentA.TestQuestion1() print("Student B's Test paper") studentB = TestPaperB() studentB.TestQuestion1() if __name__ == '__main__': main()
模板方法模式:
#!/usr/bin/env python from abc import ABCMeta,abstractmethod class AbstractClass: __metaclass__ = ABCMeta @abstractmethod def PrimitiveOperation1(self): pass @abstractmethod def PrimitiveOperation2(self): pass def TemplateMethod(self): self.PrimitiveOperation1() self.PrimitiveOperation2() class ConcreteClassA(AbstractClass): def PrimitiveOperation1(self): print('Concrete Class A Operation 1') def PrimitiveOperation2(self): print('Concrete Class A Operation 2') class ConcreteClassB(AbstractClass): def PrimitiveOperation1(self): print('Concrete Class B Operation 1') def PrimitiveOperation2(self): print('Concrete Class B Operation 2') def main(): ccA = ConcreteClassA() ccB = ConcreteClassB() ccA.TemplateMethod() ccB.TemplateMethod() if __name__ == '__main__': main()
相关文章推荐
- 设计模式之python版(七)--模板方法模式
- 大话设计模式 - 模板方法(Template Method)模式
- python设计模式之模板方法模式
- 模板方法模式(python)
- 大话设计模式之模板方法模式
- 大话设计模式---模板方法模式
- 大话设计模式C++实现-第10章-模板方法模式
- 《大话设计模式》--考题抄错会做也白搭--模板方法模式<TemplateMethod>(10)
- 《大话设计模式》之--第10章 考题抄错会做也白搭----模板方法模式
- 大话设计模式(二)代理模式 工厂方法模式 原型模式 模板方法模式 迪米特法模式 外观模式
- 大话设计模式之模板方法模式(摘录)
- 【大话设计模式】—— 模板方法模式
- 大话设计模式学习(八)——模板方法模式
- 大话设计模式之模板方法模式(Template Method Pattern)
- 大话设计模式--模板方法模式 TemplateMethod -- C++ 实现
- 《大话设计模式》-- 9.模板方法模式
- 模板方法模式Python版--考题抄错会做也白搭
- 《大话设计模式》ruby版代码:模板方法模式
- 大话设计模式——模板方法模式(C++点菜实现)