三层架构(3-tier architecture) 通常意义上的三层架构就是将整个业务应用划分为:
表现层(Presentation layer)、业务逻辑层(Business Logic Layer)、数据访问层(Data access layer)。
区分层次的目的即为了"高内聚低耦合"的思想。
高内聚低耦合,是软件工程中的概念,是判断设计好坏的标准,主要是面向对象的设计,主要是看类的内聚性是否高,耦合度是否低。
内聚就是一个模块内各个元素彼此结合的紧密程度,高内聚就是一个模块内各个元素彼此结合的紧密程度高。
所谓高内聚是指一个软件模块是由相关性很强的代码组成,只负责一项任务,也就是常说的单一责任原则。
耦合:一个软件结构内不同模块之间互连程度的度量(耦合性也叫块间联系。指软件系统结构中各模块间相互联系紧密程度的一种度量。
模块之间联系越紧密,其耦合性就越强,模块的独立性则越差,模块间耦合的高低取决于模块间接口的复杂性,调用的方式以及传递的信息。)
对于低耦合,粗浅的理解是:
一个完整的系统,模块与模块之间,尽可能的使其独立存在。
也就是说,让每个模块,尽可能的独立完成某个特定的子功能。
模块与模块之间的接口,尽量的少而简单。
如果某两个模块间的关系比较复杂的话,最好首先考虑进一步的模块划分。
这样有利于修改和组合。
ID:1,Name:zhang sanfeng,age:21
ID:2,Name:Jo,age:20
ID:2,Name:Jo,age:20
表现层(Presentation layer)、业务逻辑层(Business Logic Layer)、数据访问层(Data access layer)。
区分层次的目的即为了"高内聚低耦合"的思想。
高内聚低耦合,是软件工程中的概念,是判断设计好坏的标准,主要是面向对象的设计,主要是看类的内聚性是否高,耦合度是否低。
内聚就是一个模块内各个元素彼此结合的紧密程度,高内聚就是一个模块内各个元素彼此结合的紧密程度高。
所谓高内聚是指一个软件模块是由相关性很强的代码组成,只负责一项任务,也就是常说的单一责任原则。
耦合:一个软件结构内不同模块之间互连程度的度量(耦合性也叫块间联系。指软件系统结构中各模块间相互联系紧密程度的一种度量。
模块之间联系越紧密,其耦合性就越强,模块的独立性则越差,模块间耦合的高低取决于模块间接口的复杂性,调用的方式以及传递的信息。)
对于低耦合,粗浅的理解是:
一个完整的系统,模块与模块之间,尽可能的使其独立存在。
也就是说,让每个模块,尽可能的独立完成某个特定的子功能。
模块与模块之间的接口,尽量的少而简单。
如果某两个模块间的关系比较复杂的话,最好首先考虑进一步的模块划分。
这样有利于修改和组合。
三层架构,如下图:
1、表现层(UI):通俗讲就是展现给用户的界面,即用户在使用一个系统的时候他的所见所得。
2、业务逻辑层(BLL):针对具体问题的操作,也可以说是对数据层的操作,对数据业务逻辑处理。
3、数据访问层(DAL):该层所做事务直接操作数据库,针对数据的增添、删除、修改、查找等。
示例1:
#!/usr/bin/env python
#coding:utf-8
class Data():
#类变量products,可以通过类名直接访问,也可以通过实例来访问。
products={
'milk':{'price':1.5,'quantity':10},
'egg':{'price':0.2,'quantity':100},
'cheese':{'price':2.0,'quantity':10}
}
class BusinessLogic():
def __init__(self):
self.data=Data()
def product_list(self):
return self.data.products.keys()
def product_information(self,product):
return self.data.products.get(product,None)
class Ui():
def __init__(self):
self.business_logic=BusinessLogic()
def get_product_list(self):
print 'Product list:'
for product in self.business_logic.product_list():
print product,
print '\n'
def get_product_information(self,product):
product_info=self.business_logic.product_information(product)
if product_info:
print 'Product Information:'
print 'Name:{0},Price:{1:.2f},Quantity:{2:d}'.format(product.title(),product_info.get('price',0),product_info.get('quantity',0))
else:
print 'That product "{0}" does not exist in the records'.format(product)
def main():
ui=Ui()
ui.get_product_list()
ui.get_product_information('cheese')
ui.get_product_information('egg')
ui.get_product_information('milk')
ui.get_product_information('apple')
if __name__=='__main__':
main()
运行结果:
Product list:
cheese egg milk
Product Information:
Name:Cheese,Price:2.00,Quantity:10
Product Information:
Name:Egg,Price:0.20,Quantity:100
Product Information:
Name:Milk,Price:1.50,Quantity:10
That product "apple" does not exist in the records
示例2:
工程结构,如下:
代码如下:
student.py文件
#!/usr/bin/env python
#coding:utf-8
class student:
'''
学生类
'''
def __init__(self,ID=None,Name=None,age=None):
self.ID=ID
self.Name=Name
self.age=age
MySqlHelper.py文件
#!/usr/bin/env python
#coding:utf-8
class MySqlHelper:
'''
实现数据库具体操作的类
'''
def __init__(self, CONN_INFO):
try:
import MySQLdb
except ImportError,e:
raise e
try:
#CONN_INFO={'host':'localhost','user':'root','password':'111111','port':3306,'db':'','charset':'utf8'}
host=CONN_INFO['host']
user=CONN_INFO['user']
passwd=CONN_INFO['password']
port=CONN_INFO['port']
db=CONN_INFO['db']
charset=CONN_INFO['charset']
self.conn=MySQLdb.connect(host=host,user=user,db=db,passwd=passwd,port=port,charset=charset)#连接数据库
self.cursor=self.conn.cursor() #游标对象
except Exception,e:
raise e
'''
函数名:Finish
输入:无
功能:提交数据库操作并关闭数据库连接
输出:无
'''
def Finish(self):
try:
self.conn.commit()
self.cursor.close()
self.conn.close()
except Exception,e:
raise e
'''
函数名:CreateDB
输入:数据库名称
功能:创建数据库
输出:无
'''
def CreateDB(self,db):
try:
self.cursor.execute('drop database if exists %s' % db)
self.cursor.execute('create database %s' % db)
self.Finish()
except Exception,e:
raise e
'''
函数名:ExecuteNoQuery
输入:待执行的非查询SQL语句
功能:执行sql语句
输出:受影响的行数
'''
def ExecuteNoQuery(self,SQLstring):
try:
count=self.cursor.execute(SQLstring)
self.Finish()
return count
except Exception,e:
raise e
'''
函数名:ExecuteQuery
输入:待执行的查询SQL语句
功能:执行sql语句
输出:查询的结果集
'''
def ExecuteQuery(self,SQLstring):
try:
self.cursor.execute(SQLstring)
result=self.cursor.fetchall() #接收全部的返回结果行
self.Finish()
return result
except Exception,e:
raise e
'''
函数名:GetStringFromList
输入:待合并的列表
功能:把列表进行合并
输出:合并后的字符串
'''
def GetStringFromList(list):
str=''
for elem in list:
str+=elem
return str
Operate.py文件
#!/usr/bin/env python
#coding:utf-8
from Helper.MySqlHelper import *
from student import student
class Operate_stu:
'''
操作学生表
'''
##CONN_INFO={'host':'localhost','user':'root','password':'111111','port':3306,'db':'','charset':'utf8'}
def __init__(self,CONN_INFO):
self.CONN_INFO=CONN_INFO
def Insert(self,stu):
SqlBuilder=[]
SqlBuilder.append('insert into student ')
SqlBuilder.append("values(%s,'%s',%s)" %(stu.ID,stu.Name,stu.age))
cmd=GetStringFromList(SqlBuilder)
result=MySqlHelper(self.CONN_INFO).ExecuteNoQuery(cmd)
return result
def GetAll(self):
cmd='select * from student'
result=MySqlHelper(self.CONN_INFO).ExecuteQuery(cmd)
return result
def GetAllInfoById(self,ID):
stu=student()
SqlBuilder=[]
SqlBuilder.append('select ID,Name,age ')
SqlBuilder.append('from student where ID=%s' % ID)
cmd=GetStringFromList(SqlBuilder)
result=MySqlHelper(self.CONN_INFO).ExecuteQuery(cmd)
if result==():
return stu
result=result[0]
stu.ID=ID
stu.Name=result[1]
stu.age=result[2]
return stu
test.py文件(主文件)
#!/usr/bin/env python
#coding:utf-8
from Helper.MySqlHelper import MySqlHelper
from Operate import Operate_stu
from student import student
if __name__ == '__main__':
CONN_INFO={'host':'localhost','user':'root','password':'111111','port':3306,'db':'','charset':'utf8'}
dbname='mytestdb'
MySqlHelper(CONN_INFO).CreateDB(dbname) #创建数据库
CONN_INFO['db']=dbname
MySqlHelper(CONN_INFO).ExecuteNoQuery('create table student(ID int primary key,Name varchar(20),age int)')#创建表
#插入数据
stu=student(1,'zhang sanfeng',21)
Operate_stu(CONN_INFO).Insert(stu)
stu.ID=2
stu.Name='Jo'
stu.age=20
Operate_stu(CONN_INFO).Insert(stu)
result=Operate_stu(CONN_INFO).GetAll()
for r in result:
print 'ID:%s,Name:%s,age:%s' %(r[0],r[1],r[2])
stu=Operate_stu(CONN_INFO).GetAllInfoById(2)
print 'ID:%s,Name:%s,age:%s' %(stu.ID,stu.Name,stu.age)
运行test.py,结果如下:ID:1,Name:zhang sanfeng,age:21
ID:2,Name:Jo,age:20
ID:2,Name:Jo,age:20
(完)