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 /// summary> public interface AbstractDbFactory {/// /// Establish default connection /// summary> /// < Returns> Database connection returns> idbconnection createConnection ();
/// / / / Establish Connection object /// // // // // connection string param> /// /// Connection object < / RETURns> IDBConnection CreateConnection (String StrConn);
/// /// Establish Command object /// summary> /// Command object returns> idbcommand createcommand ();
/// /// Establish a DataAdapter object /// summary> /// DataAdapter object returnapter (iDBDataAdapter CreateDataAdapter);
/// /// According to Connection Transaction /// summary> /// Connection object param> /// Transaction object returns> iDBTRANSACTION CreateTransaction (idbconnection mydbconnection);
/// /// Established DataReader /// /////////////////////////////////// DataReader Object Returns> iDataAder CreateDataReader (iDBCommand mydbcommand); /// /// gets the connection string /// summary> /// Connection string returns> string getConnectionstring ();}}
(2) Factory.cs
Using system; using system.configuration;
namespace DbService {/// /// Factory class /// summary> public sealed class Factory {private static volatile Factory singleFactory = null; private static object syncObj = new object (); /// /// Factory class constructor /// summary> private factory () {}
/// /// Get an instance of the Factory class /// summary> /// Factory class instance returns> public static factory getInstance () {if (SingleFactory == null) {Lock (syncobj) {iffactory == NULL) {SingleFactory = new factory ();}}} Return Singlefactory;
/// /// Factory established class instance /// summary> /// Factory instance of the class returns> 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 /// summary> public class sqlfactory: Abstractory: AbstractDdbFactory {/// /// Construction function /// summary> public Sqlfactory () {}
/// /// Establish a default Connection object /// summary> /// Connection object returns> public idbconnection createconnection () {return new sqlConnection ();}
/// / / / Establish Connection object /// // // // // connection string param> /// /// Connection object < / returns> public idbconnection createConnection (String strconn) {returnnen);} /// /// Established Command object /// summary> /// Command object returns> Public IDBCommand CreateCommand () {Return New SqlCommand ();
/// /// Establish DataAdapter object /// summary> /// DataAdapter object returns> public idbdataadapter createDataAdapter () {Return New SqlDataAdapter ()
/// /// According to Connection Transaction /// summary> /// Connection object param> /// Transaction object returns> public IdbTransaction CreateTractions {Return MyDbConnection.begintransAction ();
/// // / Established DataReader /// //////////////////////////////////// DataReader Objects Returns> PUBLIC IDataReader CreateDataReader (idbcommand mydbcommand) {return mydbcommand.executeReader ();}
/// /// Get a connection string /// / summary> /// Connection string returns> 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 {/// // / /// summary> public class oledbfactory: abstractDbFactory {/// /// Constructor /// summary> public oledbFactory: AbstractDbFactory {/// () {}
/// /// Establish a default Connection object /// summary> /// Connection object returns> public idbconnection createconnection () {return new oledbConnection ();}
/// / / / Establish Connection object /// // // // // connection string param> /// /// Connection object < / returns> public idbconnection createConnection (String strconn) {Return New OledbConnection (StrConn);} /// /// Establishing Command Object /// summary> /// Command Object RETURNS> Public IDBCommand CreateCommand () {return new oledbcommand ();
/// /// Establish DataAdapter object /// summary> /// DataAdapter object returnAplic idbdataadapter createDataAdapter () {Return New OledbDataAdapter ();}
/// /// According to Connection Transaction /// summary> /// Connection object param> /// Transaction object returns> public IdbTransaction CreateTractions {Return MyDbConnection.begintransAction ();
/// // / Established DataReader /// //////////////////////////////////// DataReader Objects Returns> PUBLIC IDataReader CreateDataReader (idbcommand mydbcommand) {return mydbcommand.executeReader ();}
/// /// Get a connection string /// ///// Connection string returns> 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 {/// // //// summary> public class odbcfactory: AbstractDbFactory {/// /// summary> Public ODBCFACTory: () {}
/// /// Establish a default Connection object /// summary> /// Connection object returns> public idbconnection createconnection () {returnne odbcConnection ();}
/// / / / Establish Connection object /// // // // // connection string param> /// /// Connection object < / RETURNS> Public IDBConnection CreateConnection (String StrConn) {Return New OdbcConnection (STRCONN);
/// /// Establish Command Object /// Summary> /// Command Object Returns> Public IDBCommand CreateCommand () {Return New OdbcCommand ();
/// /// Establish DataAdapter object /// summary> /// DataAdapter object returns> public idbdataadapter createDataAdapter () {return new odbcdataadapter ();} /// /// The Connection establishment Transaction /// summary> /// Connection Object param> /// Transaction Object returns> public IDbTransaction CreateTransaction (IDbConnection myDbConnection) {Return mydbconnection.begintransaction ();
/// // / Established DataReader /// //////////////////////////////////// DataReader Objects Returns> PUBLIC IDataReader CreateDataReader (idbcommand mydbcommand) {return mydbcommand.executeReader ();}
/// /// Get a connection string /// ////// returns> 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 /// summary> Public Sealed Class Dbaccess {/// /// DBACCESS constructor // / summary> private dbaccess () {}
/// /// unconditional query operation, ie all records in the query table //// summary> /// table name param> /// column group group param> /// unconditional query results returns> 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 /// summary> /// table name param> /// column name group param> /// condition param> /// condition query results returns> 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 /// summary> /// table name param> /// column Group param> /// Value group param> 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 param> 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 /// summary> /// table name param> 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 ();}}
/// /// summary> /// table name param> /// condition param> 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 /// summary> /// table name param> /// column name group param> /// value group param> 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 /// summary> /// Table name param> /// column name group param> /// Value group param> /// condition param> 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:
appsettings>
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)