1.应用场景
(1)具有相同的操作,但是步骤中具有不同的操作细节
2.代码实现
#!/usr/bin/env python #! _*_ coding:UTF-8 _*_ from abc import ABCMeta, abstractmethod class AbstractClass(object): __metaclass__ = ABCMeta def templateMethod(self): '''在抽象类中定义了相同的步骤''' self.method1() self.method2() @abstractmethod def method1(self): pass @abstractmethod def method2(self): pass class ConcreteClass1(AbstractClass): def method1(self): '''在实现类中定义每个步骤的细节''' print "method1 of class1" def method2(self): print "method2 of class1" class ConcreteClass2(AbstractClass): def method1(self): print "method1 of class2" def method2(self): print "method2 of class2" if __name__ == "__main__": class1 = ConcreteClass1() class1.templateMethod() class2 = ConcreteClass2() class2.templateMethod()
结果:
/Users/liudaoqiang/PycharmProjects/numpy/venv/bin/python /Users/liudaoqiang/Project/python_project/day21_template/template_test.py method1 of class1 method2 of class1 method1 of class2 method2 of class2 Process finished with exit code 0