Database layer abstract factory solution archiving [continuous upgrade]

xiaoxiao2021-03-06  71

The simple factory mode is based on the data provided to it, returns an instance of a class in a few possible classes. Usually it has a common parent class and a common method, but the task performed by each method is different, and Optimized according to different data. For example, X is a base class, XY and XZ are derived from it, the XFactory class decides to return the subclass according to the parameters given, and returns the instance of that class and the programmer, because these classes have the same method, It is only different, and the instance of returning that class depends on the factory, factory functions may be complicated, but it is usually quite simple.

Next, we use an example to illustrate this simple factory mode. If we want to enter a person's name, there are two ways, one is "firstname lastname" and "fristname, lastname" form. Our task is to determine Lastname firstname comma and determined whether the name has a first step, a parent design:. public class CName {protected string frName, lName; public string getFristName () {return frName;} public string getLastName () {return lName;} } The second step, design two subclasses, which is derived from class CNAME.

They realized the interface and divided the name into two parts in the construction function. In the cfirstfirstfirst class, a simple assumption is made: all parts in front of the last space belong to firstname. Public class cfirstfirst: cname {public cfirstfirst ( String sname) {INT i = sname.trim (). Indexof (""); if (i> 0) {FRNAME = Name.substring (0, i) .trim (); lname = name.substring (i 1 ) .Trim ();} else {lname = sname; frname = "";}}} In the Lastfist class, use a calm number to the LastName. When the space or comma does not exist, both classes provide error correction processing. PUBLIC CLASS LastFrist: cname {public lastfrist (string sname) {INT i = sname.indexof (","); if (i> 0) {if (i> 0) {lname = name.substring (0, i) .Trim (); FRNAME = Name.substring (i 1) .trim ();} else {lname = sname; frname = " }}}}}} The separated name is saved in the CNAME in the base class. So there is no need for any getFirstName and getLastName methods at all in the derived class, as it has been given in the base class. Third step : Construct a simple factory. It is easy now to give a simple factory class. Only check the comma to decide to return to the instance of the class public class namefactory () {public cname getname (String sname) {INT i = sname.indexof (","); IF (i> 0) {return new lastfrist (sname);} else {return new cfirstfirst (sname);}}} fourth step.

Use factory class: string sName = "cedy hao"; NameFactory nf = new NameFactory (); CName name = nf.getName (sName); string sFristName = name.getFristName (); string sLastName = name.getLastName (); This Methods The related issues related to data are separated from other methods of the class. System class diagrams designed with abstract factory models are as follows: Database layer abstract factory solution Archive: (1) AbstractDbFactory.cs

Using system; using system.data;

Namespace dbservice {///

/// Database Abstract Factory interface /// public interface AbstractDbFactory {/// /// Establish default connection /// /// < Returns> Database connection idbconnection createConnection ();

///

/ / / Establish Connection object /// connection string /// /// Connection object < / RETURns> IDBConnection CreateConnection (String StrConn);

///

/// Establish Command object /// /// Command object idbcommand createcommand ();

///

/// Establish a DataAdapter object /// /// DataAdapter object

///

/// According to Connection Transaction /// /// Connection object /// Transaction object iDBTRANSACTION CreateTransaction (idbconnection mydbconnection);

///

/// Established DataReader /// DataReader Object iDataAder CreateDataReader (iDBCommand mydbcommand); /// /// gets the connection string /// /// Connection string string getConnectionstring ();}}

(2) Factory.cs

Using system; using system.configuration;

namespace DbService {///

/// Factory class /// public sealed class Factory {private static volatile Factory singleFactory = null; private static object syncObj = new object (); /// /// Factory class constructor /// private factory () {}

///

/// Get an instance of the Factory class /// /// Factory class instance public static factory getInstance () {if (SingleFactory == null) {Lock (syncobj) {iffactory == NULL) {SingleFactory = new factory ();}}} Return Singlefactory;

///

/// Factory established class instance /// /// Factory instance of the class public AbstractDbFactory CreateInstance () {AbstractDbFactory abstractDbFactory = null; switch (ConfigurationSettings.AppSettings [ . "DatabaseType"] ToLower ()) {case "sqlserver": {abstractDbFactory = new SqlFactory (); break;} case "oledb": {abstractDbFactory = new OleDbFactory (); break;} case "odbc": {abstractDbFactory = NEW odbcfactory (); break;}} Return AbstractDbFactory;}}} The following three classes are Factory for SQL Server dedicated connections, OLEDB connections, and ODBC connections:

(3) SQLFActory.cs

Using system; using system.data.sqlclient; using system.configuration;

Namespace DBService {///

/// Dedicated to SQLServer dedicated plants /// public class sqlfactory: Abstractory: AbstractDdbFactory {/// /// Construction function /// public Sqlfactory () {}

///

/// Establish a default Connection object /// /// Connection object public idbconnection createconnection () {return new sqlConnection ();}

///

/ / / Establish Connection object /// connection string /// /// Connection object < / returns> public idbconnection createConnection (String strconn) {returnnen);} /// /// Established Command object /// /// Command object Public IDBCommand CreateCommand () {Return New SqlCommand ();

///

/// Establish DataAdapter object /// /// DataAdapter object public idbdataadapter createDataAdapter () {Return New SqlDataAdapter ()

///

/// According to Connection Transaction /// /// Connection object /// Transaction object public IdbTransaction CreateTractions {Return MyDbConnection.begintransAction ();

///

// / Established DataReader /// DataReader Objects PUBLIC IDataReader CreateDataReader (idbcommand mydbcommand) {return mydbcommand.executeReader ();}

///

/// Get a connection string /// /// Connection string public string getConnectionstring () {string strser = configurationSettings.appsettings ["SQLServerServer"] ; string strDatabase = ConfigurationSettings.AppSettings [ "SqlServerDatabase"]; string strUid = ConfigurationSettings.AppSettings [ "SqlServerUid"]; string strPwd = ConfigurationSettings.AppSettings [ "SqlServerPwd"]; string strConnectionString = "Server =" strServer "; Database = " strDatabase "; uid = " struid "; pwd = " strpwd "; "; returnnenectionstring;}}} (4) OLEDBFACTORY.CS

Using system.data; using system.data.oledb; using system.configuration;

Namespace DBService {///

// / /// public class oledbfactory: abstractDbFactory {/// /// Constructor /// public oledbFactory: AbstractDbFactory {/// () {}

///

/// Establish a default Connection object /// /// Connection object public idbconnection createconnection () {return new oledbConnection ();}

///

/ / / Establish Connection object /// connection string /// /// Connection object < / returns> public idbconnection createConnection (String strconn) {Return New OledbConnection (StrConn);} /// /// Establishing Command Object /// /// Command Object Public IDBCommand CreateCommand () {return new oledbcommand ();

///

/// Establish DataAdapter object /// /// DataAdapter object

///

/// According to Connection Transaction /// /// Connection object /// Transaction object public IdbTransaction CreateTractions {Return MyDbConnection.begintransAction ();

///

// / Established DataReader /// DataReader Objects PUBLIC IDataReader CreateDataReader (idbcommand mydbcommand) {return mydbcommand.executeReader ();}

///

/// Get a connection string /// Connection string public string getConnectionstring () {string strprovider = configurationSettings.appsettings ["OLEDBPROVIDER"] ; string strDataSource = ConfigurationSettings.AppSettings [ "OleDbDataSource"]; string strConnectionString = "Provider =" strProvider "; Data Source =" strDataSource ";"; return strConnectionString;}}} (5) OdbcFactory.cs

Using system; using system.data.odbc; using system.configuration;

Namespace dbservice {///

// //// public class odbcfactory: AbstractDbFactory {/// /// Public ODBCFACTory: () {}

///

/// Establish a default Connection object /// /// Connection object public idbconnection createconnection () {returnne odbcConnection ();}

///

/ / / Establish Connection object /// connection string /// /// Connection object < / RETURNS> Public IDBConnection CreateConnection (String StrConn) {Return New OdbcConnection (STRCONN);

///

/// Establish Command Object /// /// Command Object Public IDBCommand CreateCommand () {Return New OdbcCommand ();

///

/// Establish DataAdapter object /// /// DataAdapter object public idbdataadapter createDataAdapter () {return new odbcdataadapter ();} /// /// The Connection establishment Transaction /// /// Connection Object /// Transaction Object public IDbTransaction CreateTransaction (IDbConnection myDbConnection) {Return mydbconnection.begintransaction ();

///

// / Established DataReader /// DataReader Objects PUBLIC IDataReader CreateDataReader (idbcommand mydbcommand) {return mydbcommand.executeReader ();}

///

/// Get a connection string /// public string getConnectionstring () {string striver = configurationSettings.appsettings ["odbcdriver"]; string strDbq = ConfigurationSettings.appsettings ["odbcdbq"]; string strconnectionstring = "driver = {" strider "}; dbq =" strdbq "; returnnectionstring;}}}

Database abstract factory implemented with C # (3)

The following is the class that is really called when the application is applied:

(6) DBACCESS.CS

Using system; using system.data;

Namespace DBService {///

/// DBACCESS class, that is, the class /// Public Sealed Class Dbaccess {/// /// DBACCESS constructor // / private dbaccess () {}

///

/// unconditional query operation, ie all records in the query table //// /// table name /// column group group /// unconditional query results public static dataset selectall (string stratlename, string [] strcolumn) {dataset ds = new dataset (); factory factory = factory .GetInstance (); abstractDbFactory abstractDbFactory = factory.CreateInstance (); IDbConnection concreteDbConn = abstractDbFactory.CreateConnection (); concreteDbConn.ConnectionString = abstractDbFactory.GetConnectionString (); concreteDbConn.Open (); IDbCommand concreteDbCommand = abstractDbFactory.CreateCommand (); IDbTransaction concreteDbTrans = AbstractDbFactory.createTransaction (ConcretedbConn); contRetedbcommand.connection = concretedbconn; contRetedbcommand.transaction = concretedbtrans; idbdataadapter concretedapter = Abstract DBFActory.createdDataAdapter (); try {string strsql = "select"; for (int i = 0; i

} CatChback (); ds.clear (); throw;} finally {contretedbconn.close ();} Return DS;

///

// / Condition query operation /// /// table name /// column name group /// condition /// condition query results public static dataset select (string stratlename, string [] strcolumn, string strcondition) { DataSet ds = new DataSet (); Factory factory = Factory.GetInstance (); AbstractDbFactory abstractDbFactory = factory.CreateInstance (); IDbConnection concreteDbConn = abstractDbFactory.CreateConnection (); concreteDbConn.ConnectionString = abstractDbFactory.GetConnectionString (); concreteDbConn.Open () ; IDbCommand concreteDbCommand = abstractDbFactory.CreateCommand (); IDbTransaction concreteDbTrans = abstractDbFactory.CreateTransaction (concreteDbConn); concreteDbCommand.Connection = concreteDbConn; concreteDbCommand.Transaction = concreteDbTrans; IDbDataAdapter concreteDbAdapter = abstractDbFactory.CreateDataAdapter (); try {string strSql = "SELECT"; for (int i = 0; i

Concretedbcommand; contRedbadapter.Fill (DS); contRedbTrans.commit ();} catch {contretedbtrans.rollback (); ds.clear (); throw;} finally {contRetedbconn.close ();} return ds;}

///

/// Single record insert /// /// table name /// column Group /// Value group public static void insert (string stratablename, string [] strcolumn, object [] strValue) {factory factory = factory.getInstance () ; abstractDbFactory abstractDbFactory = factory.CreateInstance (); IDbConnection concreteDbConn = abstractDbFactory.CreateConnection (); concreteDbConn.ConnectionString = abstractDbFactory.GetConnectionString (); concreteDbConn.Open (); IDbCommand concreteDbCommand = abstractDbFactory.CreateCommand (); IDbTransaction concreteDbTrans = abstractDbFactory.CreateTransaction (contRedbConn); contRedbcommand.connection = contRedbconn; contRetedbcommand.transaction = contRedbtrans; try {string strsql = "insert INTO" ST RTABLENAME "("; for (int i = 0; i

concreteDbCommand.CommandText = strSql; concreteDbCommand.ExecuteNonQuery (); concreteDbTrans.Commit ();} catch {concreteDbTrans.Rollback (); throw;} finally {concreteDbConn.Close ();}}

///

/// Batch records, you can insert different batch records /////////////////////////////////////////////////////////////////////////////////////> DataSet, each DataTable named table names DataSet, DataTable DataColumn in each column name called public static void InsertSet (ref DataSet ds) {Factory factory = Factory.GetInstance (); abstractDbFactory abstractDbFactory = factory.CreateInstance () ; IDbConnection concreteDbConn = abstractDbFactory.CreateConnection (); concreteDbConn.ConnectionString = abstractDbFactory.GetConnectionString (); concreteDbConn.Open (); IDbCommand concreteDbCommand = abstractDbFactory.CreateCommand (); IDbTransaction concreteDbTrans = abstractDbFactory.CreateTransaction (concreteDbConn); concreteDbCommand.Connection = concreteDbConn Concretedbcommand.Transaction = ConcretedbTrans; Try {Foreach (DataTable DT IN DS.TABLES) {Foreach (DataRow Dr in DT .Rows) {string strsql = "INSERT INTO" DT.TABLENAME "("; for (int i = 0; i

} StrSql = (dr [dt.Columns.Count - 1] " ')"); concreteDbCommand.CommandText = strSql; concreteDbCommand.ExecuteNonQuery ();}} concreteDbTrans.Commit ();} catch {concreteDbTrans.Rollback () "} Finally {contRedbconn.close ();

///

/// unconditional delete operation, that is, delete all records in the table /// /// table name public static void deleteall (String StrtableName ) {Factory factory = Factory.GetInstance (); abstractDbFactory abstractDbFactory = factory.CreateInstance (); IDbConnection concreteDbConn = abstractDbFactory.CreateConnection (); concreteDbConn.ConnectionString = abstractDbFactory.GetConnectionString (); concreteDbConn.Open (); IDbCommand concreteDbCommand = abstractDbFactory. CreateCommand (); IDbTransaction concreteDbTrans = abstractDbFactory.CreateTransaction (concreteDbConn); concreteDbCommand.Connection = concreteDbConn; concreteDbCommand.Transaction = concreteDbTrans; try {string strSql = "DELETE FROM" strTableName; concreteDbCommand.CommandText = strSql; concreteDbCommand.ExecuteNonQuery ();CONCRETEDBTRANS.COMMIT ();} catch {concretedbtrans.rollback (); throw;} finally {contRetedbconn.close ();}}

///

/// /// table name /// condition public static void Delete (string strTableName, string strCondition) {Factory factory = Factory.GetInstance (); abstractDbFactory abstractDbFactory = factory.CreateInstance (); IDbConnection concreteDbConn = abstractDbFactory.CreateConnection (); concreteDbConn.ConnectionString = abstractDbFactory.GetConnectionString () ; concreteDbConn.Open (); IDbCommand concreteDbCommand = abstractDbFactory.CreateCommand (); IDbTransaction concreteDbTrans = abstractDbFactory.CreateTransaction (concreteDbConn); concreteDbCommand.Connection = concreteDbConn; concreteDbCommand.Transaction = concreteDbTrans; try {string strSql = "DELETE FROM" strTableName "Where" strcondition; concretedbcom Mand.comMandtext = strsql; concretedbcommand.executenonquery (); contRedbtrans.commit ();} catck (); throw;} finally {contRedbconn.close ();}}

///

/// unconditional update operation, that is, update all records in the table /// /// table name /// column name group /// value group public static void updateall (string stratlename, string [] strcolumn, object [] strvalue) {factory factory = Factory.GetInstance (); AbstractDbFactory abstractDbFactory = factory.CreateInstance (); IDbConnection concreteDbConn = abstractDbFactory.CreateConnection (); concreteDbConn.ConnectionString = abstractDbFactory.GetConnectionString (); concreteDbConn.Open (); IDbCommand concreteDbCommand = abstractDbFactory.CreateCommand (); IDbTransaction Concretedbtrans = AbstractDbFactory.createTransAction (contRedbConn); contRetedbcommand.connection = contRedbConn; contRetedbConn; contRedbcommand.TransAction = ConcreteDbtrans; try {string strsql = "Update " STRTABLENAME " set "; for (int i = 0; i

} Catch {contRedbtrans.rollback (); throw;} finally {contRetedbconn.close ();}}

///

// / Condition Update Operation /// /// Table name /// column name group /// Value group /// condition public static void update (string stratlename, string [] strcolumn, object [] strValue, string strCondition) {Factory factory = Factory.GetInstance (); abstractDbFactory abstractDbFactory = factory.CreateInstance (); IDbConnection concreteDbConn = abstractDbFactory.CreateConnection (); concreteDbConn.ConnectionString = abstractDbFactory.GetConnectionString (); concreteDbConn.Open ( ); IDbCommand concreteDbCommand = abstractDbFactory.CreateCommand (); IDbTransaction concreteDbTrans = abstractDbFactory.CreateTransaction (concreteDbConn); concreteDbCommand.Connection = concreteDbConn; concreteDbCommand.Transaction = concreteDbTrans; Try {string strsql = "update" stratablename "set"; for (int i = 0; i

The final step, the root}}}} In the configuration in Web.config; concreteDbCommand.ExecuteNonQuery (); concreteDbTrans.Commit ();} catch {concreteDbTrans.Rollback (); throw;} finally {concreteDbConn.Close () Add some variables for database connection strings:

Now everything is OK, you can use different database connections (SQLServer private connections, OLEDB connections, and ODBC connections) through variables in web.config, while the entire use is still through DBACCESS, which is not affected. Attention: (Original information has been forgotten from V_V)

转载请注明原文地址:https://www.9cbs.com/read-109427.html

New Post(0)