Python Design Patterns 简明教程

Model View Controller Pattern

模型视图控制器是最常使用的设计模式。开发者发现实现这种设计模式非常容易。

Model View Controller is the most commonly used design pattern. Developers find it easy to implement this design pattern.

以下是模型视图控制器的基本架构 −

Following is a basic architecture of the Model View Controller −

architecture

现在我们看看该结构如何工作。

Let us now see how the structure works.

Model

它由纯应用逻辑组成,该逻辑与数据库交互。它包含向最终用户表示数据的所有信息。

It consists of pure application logic, which interacts with the database. It includes all the information to represent data to the end user.

View

视图表示与最终用户交互的 HTML 文件。它为用户表示模型数据。

View represents the HTML files, which interact with the end user. It represents the model’s data to user.

Controller

它充当视图和模型之间的一个中介者。它监听由视图触发的事件并向模型查询相同内容。

It acts as an intermediary between view and model. It listens to the events triggered by view and queries model for the same.

Python code

我们考虑一个称为“人”的基本对象并创建一个 MVC 设计模式。

Let us consider a basic object called “Person” and create an MVC design pattern.

Model.py

Model.py

import json

class Person(object):
   def __init__(self, first_name = None, last_name = None):
      self.first_name = first_name
      self.last_name = last_name
   #returns Person name, ex: John Doe
   def name(self):
      return ("%s %s" % (self.first_name,self.last_name))

   @classmethod
   #returns all people inside db.txt as list of Person objects
   def getAll(self):
      database = open('db.txt', 'r')
      result = []
      json_list = json.loads(database.read())
      for item in json_list:
         item = json.loads(item)
         person = Person(item['first_name'], item['last_name'])
         result.append(person)
      return result

它调用一个方法,该方法获取数据库中“人”表的全部记录。记录以 JSON 格式表示。

It calls for a method, which fetches all the records of the Person table in database. The records are presented in JSON format.

View

它显示模型中获取的所有记录。视图从不与模型交互;控制器完成这项工作(与模型和视图通信)。

It displays all the records fetched within the model. View never interacts with model; controller does this work (communicating with model and view).

from model import Person
def showAllView(list):
   print 'In our db we have %i users. Here they are:' % len(list)
   for item in list:
      print item.name()
def startView():
   print 'MVC - the simplest example'
   print 'Do you want to see everyone in my db?[y/n]'
def endView():
   print 'Goodbye!'

Controller

控制器通过 getAll() 方法与模型交互,该方法获取显示给最终用户的所有记录。

Controller interacts with model through the getAll() method which fetches all the records displayed to the end user.

from model import Person
import view

def showAll():
   #gets list of all Person objects
   people_in_db = Person.getAll()
   #calls view
   return view.showAllView(people_in_db)

def start():
   view.startView()
   input = raw_input()
   if input == 'y':
      return showAll()
   else:
      return view.endView()

if __name__ == "__main__":
   #running controller function
   start()