工厂模式提供数据源

根据数据库类型,取出数据或者是插入数据

DBAccess.cs

namespace FactoryMethod
{
    public abstract class DBAccess
    {
        abstract public DataTable GetData();
        abstract public DataTable SetData(string left, string oper, string right);
    }
    public class SqlServer : DBAccess// SQL Server,继承自DBAccess类
    {
        string connectionString = string.Empty;
        SqlConnection connection = null;
        SqlCommand cmd = null;
        SqlDataAdapter dap = null;
        DataTable table = null;
        public override DataTable GetData()//读取SQL Server数据库
        {
            try
            {
                connectionString = "Data Source=.;Initial Catalog=Calculator;Integrated Security=True;Pooling=False";
                connection = new SqlConnection(connectionString);
                cmd = new SqlCommand("select txtLeft,txtOper,txtRight from Question", connection);
                dap = new SqlDataAdapter(cmd);
                table = new DataTable();
                dap.Fill(table);
                return table;
            }
            catch
            {
                return null;
            }
            finally
            {
                table.Dispose();
            }
        }
        public override DataTable SetData(string left,string oper,string right) //向SQL Server数据库表中插入记录
        {
            connectionString = "Data Source=.;Initial Catalog=Calculator;Integrated Security=True;Pooling=False";
            connection = new SqlConnection(connectionString);
            string insertInfo = "insert into Question(txtLeft,txtOper,txtRight) values('" + left + "','" + oper + "','" + right + "')";
            SqlCommand sqlcmd = new SqlCommand(insertInfo, connection);
            connection.Open();
            try
            {
                sqlcmd.ExecuteNonQuery();
            }
            catch
            {
                return null;
            }
            connection.Close();
            return null;
        }
    }
    public class Access : DBAccess//Access,继承自DBAccess类
    {
        string connectionString = string.Empty;
        OleDbConnection connection = null;
        OleDbCommand cmd = null;
        OleDbDataAdapter dap = null;
        DataTable table = null;
        public override DataTable GetData()//读取Access数据库
        {
            try
            {
                connectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\\Calculator.mdb";
                connection = new OleDbConnection(connectionString);
                cmd = new OleDbCommand("select txtLeft,txtOper,txtRight from Question", connection);
                dap = new OleDbDataAdapter(cmd);
                table = new DataTable();
                dap.Fill(table);
                return table;
            }
            catch
            {
                return null;
            }
            finally
            {
                table.Dispose();
            }
        }
        public override DataTable SetData(string left, string oper, string right) //向Access数据库表中插入记录
        {
            connectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\\Calculator.mdb";
            connection = new OleDbConnection(connectionString);
            string insertInfo = "insert into Question(txtLeft,txtOper,txtRight) values('" + left + "','" + oper + "','" + right + "')";
            OleDbCommand OleDbcmd = new OleDbCommand(insertInfo, connection);
            connection.Open();
            try
            {
                OleDbcmd.ExecuteNonQuery();
            }
            catch
            {
                return null;
            }
            connection.Close();
            return null;
        }
    }
}

 

抽象工厂类

CreateDBFactory.cs

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

namespace FactoryMethod
{
    public abstract class CreateDBFactory// 抽象工厂类
    {
        abstract public DBAccess createDataBase(); // 工厂方法
    }
    public class SqlServerFactory : CreateDBFactory// SQL Server工厂,继承自CreateDBFactory类
    {
        // 返回SQL Server数据库
        public override DBAccess createDataBase()
        {
            return new SqlServer();
        }
    }
    public class AccessFactory : CreateDBFactory//Access工厂,继承自CreateDBFactory类
    {
        public override DBAccess createDataBase()// 返回Access数据库
        {
            return new Access();
        }
    }
}

  

FrmQuestion.cs

namespace FactoryMethod
{
    public partial class FrmQuestion : Form
    {
        public FrmQuestion()
        {
            InitializeComponent();
            this.RSql.CheckedChanged += new EventHandler(rbtn_CheckedChanged);
            this.RAccess.CheckedChanged += new EventHandler(rbtn_CheckedChanged);
            this.RTxt.CheckedChanged += new EventHandler(rbtn_CheckedChanged);
        }
        private string selectedDB = null;
        void rbtn_CheckedChanged(object sender, EventArgs e)
        {
            selectedDB = ((RadioButton)sender).Text;
            this.lblSelectedInfo.Text = "您选择了" + selectedDB + "数据源!";
            this.gboxSelect.Enabled = false;
            this.btnShowData.Enabled = true;
        }
        private void btnSelectNewDB_Click(object sender, EventArgs e)//切换数据库
        {
            if (this.gboxSelect.Enabled == true)
            {
                MessageBox.Show("您还没有选择数据源,请选择!", "提示!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            this.RSql.Checked = false;
            this.RAccess.Checked = false;
            this.RTxt.Checked = false;
            this.gboxSelect.Enabled = true;
            this.lblSelectedInfo.Text = null;
            this.btnShowData.Enabled = false;
            this.dgvData.DataSource = null;
        }
        private void btnShowData_Click(object sender, EventArgs e)//在DataGridView中显示数据
        {
            switch (selectedDB)
            {
                case "SQL Server":
                    this.dgvData.DataSource = new SqlServerFactory().createDataBase().GetData();
                    string selInfo = "select ID,txtLeft,txtOper,txtRight from Question";
                    string connectionString = "Data Source=.;Initial Catalog=Calculator;Integrated Security=True;Pooling=False";
                    SqlConnection conn = new SqlConnection(connectionString);
                    SqlDataAdapter adapter;
                    DataSet ds = new DataSet();
                    DataTable dt;
                    conn.Open();
                    adapter = new SqlDataAdapter(selInfo, conn);
                    adapter.Fill(ds, "Question");
                    dt = ds.Tables["Question"];
                    comboxID.ValueMember = "ID";
                    comboxID.DataSource = dt;
                    conn.Close();
                    break;
                case "Txt":
                    string[] n1 = new string[100];
                    n1 = File.ReadAllLines("Left.txt");
                    txtLeft.Text = n1[0];
                    string[] n2 = new string[100];
                    n2 = File.ReadAllLines("Oper.txt");
                    txtOper.Text = n2[0];
                    string[] n3 = new string[100];
                    n3 = File.ReadAllLines("Right.txt");
                    txtRight.Text = n3[0];
                    break;
                case "Access":
                    this.dgvData.DataSource = new AccessFactory().createDataBase().GetData();
                    string selInfo1 = "select ID,txtLeft,txtOper,txtRight from Question";
                    string connectionString1 = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\\Calculator.mdb";
                    OleDbConnection conn1 = new OleDbConnection(connectionString1);
                    OleDbDataAdapter adapter1;
                    DataSet ds1 = new DataSet();
                    DataTable dt1;
                    conn1.Open();
                    adapter1 = new OleDbDataAdapter(selInfo1, conn1);
                    adapter1.Fill(ds1, "Question");
                    dt1 = ds1.Tables["Question"];
                    comboxID.ValueMember = "ID";
                    comboxID.DataSource = dt1;
                    conn1.Close();
                    break;
                default:
                    break;
            }
        }
        private void btnAdd_Click(object sender, EventArgs e)     //在DataGridView中插入数据
        {
            string symbol = txtOper.Text;
            string a = txtLeft.Text;
            string b = txtRight.Text;
            switch (selectedDB)
            {
                case "SQL Server":
                    this.dgvData.DataSource = new SqlServerFactory().createDataBase().SetData(a, symbol, b);
                    MessageBox.Show("数据插入成功!");
                    txtLeft.Clear();
                    txtOper.Clear();
                    txtRight.Clear();
                    break;
                case "Txt":
                    StreamWriter Left = File.AppendText("Left.txt");
                    Left.WriteLine(txtLeft.Text);
                    Left.Close();
                    StreamWriter Oper = File.AppendText("Oper.txt");
                    Oper.WriteLine(txtOper.Text);
                    Oper.Close();
                    StreamWriter Right = File.AppendText("Right.txt");
                    Right.WriteLine(txtRight.Text);
                    Right.Close();
                    MessageBox.Show("数据插入成功!");
                    txtLeft.Clear();
                    txtOper.Clear();
                    txtRight.Clear();
                    break;
                case "Access":
                    this.dgvData.DataSource = new AccessFactory().createDataBase().SetData(a, symbol, b);
                    MessageBox.Show("数据插入成功!");
                    txtLeft.Clear();
                    txtOper.Clear();
                    txtRight.Clear();
                    break;
                default:
                    break;
            }
        }
        private void btnNext_Click(object sender, EventArgs e)
        {
            int n = 1;
            string[] n1 = new string[100];
            n1 = File.ReadAllLines("Left.txt");
            txtLeft.Text = n1[n];
            string[] n2 = new string[100];
            n2 = File.ReadAllLines("Oper.txt");
            txtOper.Text = n2[n];
            string[] n3 = new string[100];
            n3 = File.ReadAllLines("Right.txt");
            txtRight.Text = n3[n];
            n++;
        }
        private void comboxID_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (selectedDB)
            {
                case "SQL Server":
                    string selInfo = "select txtLeft,txtOper,txtRight from Question where ID='" + comboxID.Text.ToString().Trim() + "'";
                    string connectionString = "Data Source=.;Initial Catalog=Calculator;Integrated Security=True;Pooling=False";
                    SqlConnection conn = new SqlConnection(connectionString);
                    SqlCommand sqlcmd = new SqlCommand(selInfo, conn);
                    SqlDataReader sdr;
                    conn.Open();
                    sdr = sqlcmd.ExecuteReader();
                    if (sdr.Read())
                    {
                        txtLeft.Text = sdr["txtLeft"].ToString();
                        txtOper.Text = sdr["txtOper"].ToString();
                        txtRight.Text = sdr["txtRight"].ToString();
                    }
                    conn.Close(); 
                    break;
                case "Access":
                    string selInfo1 = "select txtLeft,txtOper,txtRight from Question where ID='" + comboxID.Text.ToString().Trim() + "'";
                    string connectionString1 = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\\Calculator.mdb";
                    OleDbConnection conn1 = new OleDbConnection(connectionString1);
                    OleDbCommand sqlcmd1 = new OleDbCommand(selInfo1, conn1);
                    OleDbDataReader sdr1;
                    conn1.Open();
                    sdr1 = sqlcmd1.ExecuteReader();
                    if (sdr1.Read())
                    {
                        txtLeft.Text = sdr1["txtLeft"].ToString();
                        txtOper.Text = sdr1["txtOper"].ToString();
                        txtRight.Text = sdr1["txtRight"].ToString();
                    }
                    conn1.Close(); 
                    break;
                default:
                    break;
            }
        }
        private void textBox4_KeyDown(object sender, KeyEventArgs e)
        {
            string symbol = txtOper.Text;
            double a = Convert.ToDouble(txtLeft.Text);
            double b = Convert.ToDouble(txtRight.Text);
            Context contex = null;
            if (symbol == "+")
            {
                contex = new Context(new Add());    //加法策略
            }
            else if (symbol == "-")
            {
                contex = new Context(new Sub());    //减法策略
            }
            else if (symbol == "*")      //若为乘号
            {
                contex = new Context(new Mul());    //乘法策略
            }
            else if (symbol == "/")      //若为乘号
            {
                contex = new Context(new Div());    //除法策略
            }
            string answer = contex.Cal(a, b, symbol).ToString();  //用answer来存计算出来的答案,此时已经计算出a,b两个数的运算结果。
            if (e.KeyCode == Keys.Enter)              //回车操作
            {
                string result = txtLeft.Text + txtOper.Text + txtRight.Text;//把运算式子存在result里面       
                if (textBox4.Text == answer)                                  //如果输入答案与计算出的answer相等
                {
                    MessageBox.Show("回答正确!");                            //弹出回答正确
                    listBox1.Items.Add(result + "=" + textBox4.Text.Trim() + "");//并把运算式子存在listbox里 
                }
                else                                                          //如果答错
                {
                    MessageBox.Show("答题错误!");                            //弹出答题错误
                    listBox1.Items.Add(result + "=" + textBox4.Text.Trim() + "×");//同样把运算式子放在listbox
                }
                textBox4.Clear();
            }
        } 
    }
}

 

1.新建一个数据库

工厂模式提供数据源_第1张图片

2.单选按钮选中数据库,从而确定数据库的类型,并且往Txt数据源插入数据

工厂模式提供数据源_第2张图片

3.此时程序自动新建了三个txt文本文件来作为数据源

 

4.txt数据源答题时

工厂模式提供数据源_第3张图片

5.使用txt数据源做了2题后切换数据源,此时同样可以使用SQL Server数据源来答题。

工厂模式提供数据源_第4张图片

你可能感兴趣的:(工厂模式提供数据源)