C # Design mode Abstract Factory (AbstractFactory)

xiaoxiao2021-03-06  20

1. Why use abstract factories? Benefits of abstract factory

Here I still can't think of what benefits temporarily.

I think it is to use the interface to implement the package, so that the specific work is handed over to its subclass. So this should not be able to count the advantages of an abstract factory, and can only count the advantages of an interface.

2. How to use abstract factories in C #?

Ok, let's take a look at how to achieve it.

For example, we have to write a component connected to the database, support both SQLServer, but also support OLEDB, then we can use the AbstractFactory mode.

First define an interface:

Public interface IDBHELPER

{

Void ExecutenonQuery ();

DataSet ExecuteFordataset (String SQL);

}

Then define two classes (one is SQLServer, one is OLEDB) to inherit the IDBHELPER interface:

INTERNAL CLASS SQLDBHELPER: IDBHELPER

{

Public SqldBhelper ()

{

}

Public void executenonQuery ()

{

}

Public Dataset ExecuteFordataset (String SQL)

{

// A method for achieving SQL Server

Return NULL;

}

}

INTERNAL CLASS OLEDBHELPER: IDBHELPER

{

Public oledbhelper ()

{

}

Public void executenonQuery ()

{

}

Public Dataset ExecuteFordataset (String SQL)

{

// A method of achieving OLEDB

Return NULL;

}

}

Then, to 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, let us call this factory:

Public Class AbstractFactoryTestFactoryTest

{

Public void testmethod ()

{

IDBHELPER SQLDB = DBHELPERFAACTORY.CREATEDBHELPER (1);

Sqldb.executenonQuery ();

}

}

At this time, we can easily call the database component. When calling the createDbhelper method, the incoming parameter is 1, then call SQLDBHELPER, the incoming parameter is 2, then the OLEDBHELPER is called. Of course, you can also turn it into an enumeration type, which is more convenient.

Such a write method is also more advantageous. For example, when you have to add an ORACLEDBHELPER, you only need to add a class, change a method (createDbhelper).

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

New Post(0)