1. Why use abstract factory? Benefits of using abstract factory
I cannot think of any benefits for the moment.
I think it is to use interfaces to encapsulate its sub-classes so that specific work can be handed over to its sub-classes. Therefore, this should not be regarded as an abstract factory advantage, but an interface advantage.
2. How to Use abstract factory in C?
Okay. Let's take a look at how to implement it.
For example, if we want to write a database connection component that supports both sqlserver and oledb, then we can use the AbstractFactory design mode.
First define an interface:
Public interface IDbHelper
{
Void ExecuteNonQuery ();
DataSet ExecuteForDataSet (string SQL );
}
Then define two classes (sqlserver and oledb) to inherit the IdbHelper interface:
Internal class SqlDbHelper: IDbHelper
{
Public SqlDbHelper ()
{
}
Public void ExecuteNonQuery ()
{
}
Public DataSet ExecuteForDataSet (string SQL)
{
// The SQL Server Implementation Method
Return null;
}
}
Internal class OleDbHelper: IDbHelper
{
Public OleDbHelper ()
{
}
Public void ExecuteNonQuery ()
{
}
Public DataSet ExecuteForDataSet (string SQL)
{
// How to implement oledb
Return null;
}
}
Then, define a factory class:
Public class DbHelperFactory
{
Public static IDbHelper CreateDbHelper (int DbType)
{
Switch (DbType)
{
Case 1:
Return new SqlDbHelper ();
Case 2:
Return new OleDbHelper ();
Default:
Return null;
}
}
}
Finally, we will call this factory class:
Public class AbstractFactoryTest
{
Public void TestMethod ()
{
IDbHelper sqldb = DbHelperFactory. CreateDbHelper (1 );
Sqldb. ExecuteNonQuery ();
}
}
At this time, we can easily call the database component. When the CreateDbHelper method is called, the input parameter is 1, that is, the SqlDbHelper class is called, and the input parameter is 2, the class OleDbHelper is called. Of course, you can also change the input parameter to the enumeration type, which makes it more convenient.
This method is more conducive to expansion. For example, if you want to add an OracleDbHelper later, you only need to add another class and change a method (CreateDbHelper.