C Sharp to Web

I Love This Code
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

通过实例了解抽象工厂(一)数据组件层

Posted on 2007-05-07 01:42  落花游鸿  阅读(2612)  评论(9)    收藏  举报
本文主要面向刚接触.Net不就的朋友,所以我尽量用通俗易懂的语言叙述。
文章通过一个简单的数据库操作示例阐述抽象工厂的实际应用。

一、实例介绍

  本示例为新闻的添加、删除、编辑、列表显示操作

    数据库:FactoryDB
    表:News
    字段 ID int
         Title nvarchar(50)
         Content ntext


二、项目的建立

  新建项目-Visual Studio解决方案-空白解决方案,这里需要注意的是项目建好以后必须首先新建一个解决方案文件夹,否则当你添加任何新
< br>建项目的时候解决方案都会在方案资源管理器中消失,具体原因我也没弄明白。



接下来我们要建立Components类库
< br>此类主要存放业务对象实体、业务逻辑对象、数据抽象工厂请看下图:



业务对象实体News的具体实现:

using System;

namespace Components
{
    
public class News
    {
        
private int id;
        
private string title;
        
private string content;

        
public int ID
        {
            
get { return id; }
            
set { id = value; }
        }
        
public string Title
        {
            
get { return title; }
            
set { title = value; }
        }
        
public string Content
        {
            
get { return content; }
            
set { content = value; }
        }
    }
}


数据抽象工厂Factory的具体实现

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Configuration;
using System.Web.Caching;
using System.Web;
using System.Data;
using System.Text;

namespace Components
{
    
public abstract class Factory
    {   
        
//取得Web项目中配置文件Web.Config里WebDAL节点的设置 节点配置为
    
//<appSettings>
    
//    <add key="WebDAL" value="SQLServerDAL"/>
    
//</appSettings>
        private static readonly string path = ConfigurationManager.AppSettings["WebDAL"]; 
        
private static Factory fac = null;

        
public Factory() { }

        
public static Factory Instance()
        {
            
if (fac == null)
                fac 
= (Factory)Assembly.Load(path).CreateInstance(path + "." + path);//利用反射实例化
            return fac;
        }

        
public abstract List<News> GetNews(); //定义新闻列表的获取方法,此方法将在后面的数据层中实现
         
//public abstract int News_CreateUpdateDelete();
        public static News NewsIDataReader(IDataReader dr) //定义数据抽取器,数据层中实现GetNews方法时被调用
        {
            News news 
= new News();
            news.ID 
= (int)dr["ID"];
            news.Title 
= dr["Title"].ToString();
            news.Content 
= dr["Content"].ToString();
            
return news;
        }
    }
}


业务逻辑对象 NewsS 的具体实现

using System;
using System.Collections.Generic;
using System.Text;

namespace Components
{
    
public class NewsS
    {
        
public List<News> GetNews()
        {
            Factory fac 
= Factory.Instance();      //工厂实例化
            return fac.GetNews();                  //返回数据层中的执行结果,该结果构造一个News范型
        }
    }
}