一、复合模式简介
复合模式将两个或更多模式组合成常见或普遍性问题的解决方案。复合模式不是同时使用的一组模式,而是一个问题的通用解决方案。
二、模型-视图-控制器模式
1.概念
1.1 模型:声明一个存储和操作数据的类
定义针对数据的所有操作(例如创建、修改、删除),并提供与数据使用方式有关的方法
1.2 视图:声明一个类来构建用户界面和显示数据
它提供相应的方法,帮助我们根据上下文和应用程序的需要来构建web或GUI界面。它不应该包含自己的任何逻辑,而只应用来显示接收到的数据。
1.3 控制器:声明一个连接模型和视图的类
控制器从请求接收数据,并将其发送到系统的其他部分。他需要提供用于路由请求的方法。
1.4 客户端:声明一个类,根据某些操作来获得某些结果
1.5 适用场景
1.5.1 当需要更改展示方式而不更改业务逻辑时。
1.5.2 多个控制器可用于使用多个视图来更改用户界面上的展示。
1.5.3 再次重申,当模型改变时,视图无需改动,因为他们是相互独立的。
1.6 主要目的
1.6.1 将数据和数据的展示隔离开来。
1.6.2 使类的维护和实现更加简单。
1.6.3 灵活地改变数据的存储和显示方式,两者都是独立的,因此可以灵活修改。
2.例子
class Model(object):
services = {
'email':{'number':1000,'price':2,},
'sms':{'number':1000,'price':10,},
'voice':{'number':1000,'price':15,},
}
class View(object):
def list_services(self,services):
for svc in services:
print (svc,'')
def list_pricing(self,services):
for svc in services:
print ('For',Model.services[svc]['number'],
svc,"message you pay $",
Model.services[svc]['price'])
class Controller(object):
def __init__(self):
self.model = Model()
self.view = View()
def get_services(self):
services = self.model.services.keys()
return(self.view.list_services(services))
def get_pricing(self):
services = self.model.services.keys()
return(self.view.list_pricing(services))
class Client(object):
controller = Controller()
print ("Services Provided:")
controller.get_services()
print ("Services for Services:")
controller.get_pricing()
三、MVC设计模式的UML类图
class Model(object):
def logic(self):
data = "Got it"
print ("Model: Crunching data as per business logic")
return data
class View(object):
def updata(self,data):
print ("View:Updating the view with results: ",data)
class Controller(object):
def __init__(self):
self.model = Model()
self.view = View()
def interface(self):
print ("Controller: Relayed the Client asks")
data = self.model.logic()
self.view.updata(data)
class Client(object):
print ("Client: asks for certain information")
controller = Controller()
controller.interface()
四、MCV 模式的优点
1. 使用MVC,开发人员可以将软件应用分为三个主要部分:模型、视图、控制器。这有助于提高可维护性,强制松耦合,并降低复杂性。
2. MVC允许对前端进行独立更改,而对后端逻辑无需任何修改或只需进行很少的更改,因此开发工作仍可以独立运行。
3. 类似地,可以更改模型或业务逻辑,而无需对视图进行任何更改。
4. 此外,可以更改控制器,而不会对视图或模型造成任何影响。
5. MVC还有助于招聘具有特定能力的人员,例如平台工程师和UI工程师,他们可以在自己的专业领域独立工作。
五、常见问答
1.MVC 是不是一种模式?为什么被称为复合模式?
本质上来说,复合模式就是相互配合共同解决软件应用程序开发中的大型设计问题的一组模式。MVC模式是最受欢迎的同事也是应用最广泛的复合模式。
2.MVC只能御用网站?
不,网站是描述MVC的最好的例子。
3.多个视图可以使用多个模型吗?
是的,通常你最终会遇到多个模型整理数据并在一个视图中显示的情况。一对一地映射在当今的网络应用程序世界中是非常罕见的。
本系列项目代码地址:Python-design-pattern