Oracle培訓:抽象工廠中加入Oracle
Oracle培訓:抽象工廠中加入Oracle,在設計模式中介紹過抽象工廠設計模式(Abstract Factory),抽象工廠有四種關鍵角色:抽象工廠、實體工廠、抽象產品、實體產品。抽象工廠模式實現原理強調的是對象組合機制,由在“父工廠”內定義不同的“子工廠”對象來負責不同的目標對象的創建,也就是說利用實體產品由抽象產品來約束,而由實體工廠來創建,實體工廠則由抽象工廠約束,可以有效的發揮工廠模式管理清晰的優點。
案例2:采用抽象工廠模式實現在學員信息管理系統中支持Access、SQLServer以及Oracle三套數據庫的切換(以學員基本信息模塊為例),以學員基本信息模塊為例給出概要的實現,并實現展示所有學生信息功能。
案例分析:本例是抽象工廠課堂案例的延續,需要在項目中多添加一個Oracle數據庫,實體產品是數據訪問對象,三套數據庫相當于有三套數據庫訪問對象,通過三個實體工廠管理三套數據庫訪問對象,最后使用抽象工廠管理三個實體工廠。
實現步驟:
1. 在Oracle數據庫中使用Sql語句新建Infos表,并添加約束和表數據,如圖3所示:
圖3 Student表數據
2. 在VS2008中創建空白解決方案,命名為Test.sln。
3. 在解決方案中添加表示層,并添加StudentList.aspx頁面。
4. 在解決方案中添加模型層,根據上面的表結構新建Student.cs實體類。
代碼演示:Student類
public class Student { string stuID;
public string StuID { get { return stuID; } set { stuID = value; } }
/** * 其他成員… … */ } |
5. 在解決方案中添加數據訪問層IDAL(抽象產品)。
代碼演示:抽象產品
public interface IStudentService { //獲取所有學生信息 IList<Student> GetAllStudents(); } |
6. 在解決方案中添加數據訪問層DAL(實體產品),并利用文件夾將不同的實體產品分類,如圖4所示。
圖4 實體產品
代碼演示:實體產品
/// <summary> /// 獲得所有學生信息 /// </summary> /// <returns>所有學生信息集合</returns> public IList<Student> GetAllStudents() { //創建SQL語句 string sql = "select * from sys.infos"; //創建泛型集合 IList<Student> students = new List<Student>(); //執行SQL語句得到結果集 OracleDataReader odr = dbh.ExecuteReader(sql); //遍歷結果集 while(odr.Read()) { Student student = new Student();
student.StuID = Convert.ToString(odr["StuID"]); student.StuName = Convert.ToString(odr["StuName"]); student.StuAddress = Convert.ToString(odr["StuAddress"]); student.Seat = Convert.ToInt32(odr["Seat"]); student.Gender = Convert.ToString(odr["Gender"]); student.EnRollDate = Convert.ToDateTime(odr["EnRollDate"]); student.ClassNo = Convert. ToString (odr["ClassNo"]); //添加到泛型集合 students.Add(student); } //返回 return students; } |
7. 在解決方案中添加業務邏輯層,命名為StudentManager.cs。
代碼演示:BLL層
/// <summary> /// 獲取所有學生信息 /// </summary> /// <returns>所有學生信息集合</returns> public IList<Student> GetAllStudents() { //利用抽象工廠創建實體工廠 Factory factory = Factory.CreateFactory(); //利用工廠創建產品 IStudentService iss = factory.GetStudentService(); return iss.GetAllStudents(); } |
8. 在解決方案中添加抽象工廠,并添加相應實體工廠,如圖5所示。
圖5 抽象工廠
代碼演示:抽象工廠
//抽象工廠 public abstract class Factory { public static Factory CreateFactory() { //采用反射技術得到配置文件中的配置信息 string factoryType = Config.FactoryType; Factory factory = (Factory)System.Reflection.Assembly.Load("DBFactory").CreateInstance(factoryType); return factory; }
//定義子類(實體工廠)的操作規則 public abstract IStudentService GetStudentService(); } |
9. 在表示層添加數據展示控件,通過設定屬性綁定數據提取方法,實現案例目標。
-
標簽錯誤:<!-- #Label#
labelId=20160707140604
moduleId=1
classId=12231768634
orderby=2
fields=url,title,u_info
attribute=
datatypeId=22192428132
recordCount=3
pageSize=
<htmlTemplate><dt><img src="/images/index_26${index}.jpg" width="100" height="62" /><a href="$url" title="${title}">${title}</a><span>${api.left(u_info,60)}</span></dt></htmlTemplate>
-->
- 我要參加技術沙龍