Skip to content

Instantly share code, notes, and snippets.

@simongarisch
Created October 16, 2019 23:04
Show Gist options
  • Save simongarisch/569e7413ba7e01338c91ddbdde29aa51 to your computer and use it in GitHub Desktop.
Save simongarisch/569e7413ba7e01338c91ddbdde29aa51 to your computer and use it in GitHub Desktop.
Python structural patterns - MVC
"""
The Separation of Concerns (SoC) is a design principle for separating a computer program into distinct sections.
With the Model View Controller (MVC) pattern we separate the out the data model, our visual representation or view,
and the controller that decides what model data to show on the view.
"""
class PriceModel:
stocks = {
"FB": "Facebook",
"AMZN": "Amazon",
"AAPL": "Apple",
"NFLX": "Netflix",
"GOOG": "Google",
}
def get_stock_name(self, stock_code):
return self.stocks[stock_code]
def get_stock_code(self, stock_name):
reverse_dict = {v: k for k, v in self.stocks.items()}
return reverse_dict[stock_name]
class PriceView:
def __init__(self):
print("***** MVC Example *****")
details = [
"Here we can do lookups for FAANG stocks! Options are:",
"- 's' to lookup by stock name.",
"- 't' to lookup by stock ticker.",
"- 'e' to exit.",
]
print("\n".join(details))
self.underline()
def underline(self):
print("*" * 40)
def error(self, error_string):
print("Error: %s" % error_string)
def options(self):
msg = "Make your choice..."
return input(msg)
def choose_lookup_string(self):
msg = "Choose your lookup string..."
return input(msg)
def show_output(self, output):
print(output)
class PriceController:
def __init__(self):
self.model = PriceModel()
self.view = PriceView()
self.start()
def start(self):
while True:
choice = self.view.options()
choice = str(choice).lower()
if choice == "e":
self.view.show_output("Exiting...")
break
if choice not in ["s", "t"]:
self.view.error("%s is not a valid choice!" % choice)
else:
lookup = self.view.choose_lookup_string()
try:
if choice == "s":
output = self.model.get_stock_code(lookup)
else:
output = self.model.get_stock_name(lookup)
self.view.show_output(output)
except Exception as e:
self.view.error(e)
self.view.underline()
if __name__ == "__main__":
PriceController()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment