Skip to content

Instantly share code, notes, and snippets.

@courtneyzhan
Created January 22, 2022 06:49
Show Gist options
  • Save courtneyzhan/a7f716cabdccab00a212b63f638dec11 to your computer and use it in GitHub Desktop.
Save courtneyzhan/a7f716cabdccab00a212b63f638dec11 to your computer and use it in GitHub Desktop.
Example of Software Design Pattern's Template Method.
class ProjectFile:
safe_save = 0
def __init__(self, file_name):
self.file_name = file_name
def save(self):
print("{", self.file_name, "} Saving ...")
def safe_save(self):
if (self.validate()):
self.reformat()
self.save()
else:
print("{", self.file_name, "} Not saved")
class RubyFile(ProjectFile):
def validate(self):
print("[RubyFile] Validate")
return True
def reformat(self):
print("[RubyFile] Reformatting")
class XmlFile(ProjectFile):
def validate(self):
print("[XmlFile] Validate")
return True
def reformat(self):
print("[XmlFile] Reformatting")
class PdfFile(ProjectFile):
def validate(self):
print("[PdfFile] Skip Validate")
return False
def reformat(self):
print("[PdfFile] Reformatting")
ruby_file = RubyFile("bar.rb")
xml_file = XmlFile("foo.xml")
pdf_file = PdfFile("wise.pdf")
xml_file.safe_save()
pdf_file.safe_save()
ruby_file.safe_save()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment