Design 1. Why do we use abstract factories? The benefits of using abstract factories
I can't think of any good here for the time being.
I think it is to use the interface to encapsulate its subclasses, so that the specific work to give its subclasses to do. Therefore, this should not be considered as an abstraction of the advantages of the factory, can only count the advantages of the interface.
2. How to use abstract factory in C #?
Okay, let's take a look at how to achieve
For example, we're going to write a component that connects the database to both SQL Server and OLE DB, so we can use the abstractfactory design pattern.
First define an interface:
public interface Idbhelper
{
void ExecuteNonQuery ();
DataSet executefordataset (String sql);
}
Then define two classes (one is SQL Server, one is OLE DB) to inherit Idbhelper this interface:
Internal class Sqldbhelper:idbhelper
{
Public Sqldbhelper ()
{
}
public void ExecuteNonQuery ()
{
}
Public DataSet Executefordataset (String sql)
{
Here's how to implement SQL Server
return null;
}
}
Internal class Oledbhelper:idbhelper
{
Public Oledbhelper ()
{
}
public void ExecuteNonQuery ()
{
}
Public DataSet Executefordataset (String sql)
{
Here's how to implement OLE DB
return null;
}
}
Then, to define a factory class:
public class Dbhelperfactory
{
public static idbhelper createdbhelper (int DbType)
At this time we can easily invoke the database components, when the Createdbhelper method is invoked, the incoming parameter is 1, then call Sqldbhelper this class, pass the parameter is 2, then call Oledbhelper this class. Of course, the incoming parameters you can also make it into an enumerated type, which is more convenient.
This kind of writing is also more conducive to expansion, such as the future to add a oracledbhelper, you just need to add a class, change a method (Createdbhelper) on it.
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.