C # 39 Abstract Factory mode

Source: Internet
Author: User

In software system, it is often faced with the creation of "a series of interdependent objects", and the creation of more series objects often exists because of the change of demand. How to deal with this change? How do you bypass the general object creation method (new), which provides a "encapsulation mechanism" to avoid tight coupling between the client program and this "multi-series concrete object creation work"? That's the abstract factory pattern we're talking about.

Focus:

? Abstract Factory Pattern Concept

? Model diagram of the abstract factory model

? Abstract Factory mode accesses multiple databases

Preview Lessons:

? What is abstract Factory mode

? How to access multiple databases using abstract Factory mode

5.1 Abstract Factory Mode overview

Abstract Factory is a kind of creation pattern, it is to solve the problem that brings about when instantiation. The intent of this pattern is to provide an interface that is responsible for creating a series of "related or interdependent objects" without specifying their specific classes.

5.1.1 How to change database

If a company has already done a business e-commerce site, using SQL Server as a database, and now a project similar to the needs of the enterprise, but the company to save money, want to use Access, then what?

The use of SQL Server and access on the ADO is different on SQL Server using the SqlConnection, SqlCommand, and System.Data.SqlClient namespaces. SqlParameter, SqlDataReader, SqlDataAdapter, and Access uses the corresponding object under the System.Data.OleDb namespace.

In addition, there are many differences in SQL syntax, such as when inserting data, access must insert into and SQL Server can not into;sqlserver in the GETDATE () in Access, need to be rewritten as now (); There is a string function substring in SQL Server, and access is not available at all. Also, use "[]" for keywords in access, or you can get an error.

Therefore, if there are multiple projects of the same type, and the database is different, the amount of work to modify the code is unprecedented, then there is a good way to enable us to perform different operations according to different databases?

5.1.2 data Access programs that use abstract Factory mode




"Abstractproducta and ABSTRACTPRODUCTB are two abstract products that are abstract because they are likely to have two different implementations, while ProductA1, ProductA2, and ProductB1, ProductB2 is the implementation of a specific classification of two abstract products, such as ProductA1 can be understood as sqlserveruser, and ProductB1 is Accessuser. ”

"So, Ifactory is an abstract factory interface, which should contain all the abstract methods of product creation. and ConcreateFactory1 and ConcreateFactory2 are concrete factories. Just like Sqlserverfactory and Accessfactory. Typically, you create an instance of the Concreatefactory class at run time, and the specific factory creates a product object with a specific implementation, that is, to create a different product object, the client should use a different specific factory. ”

Advantages and disadvantages of 5.1.3 abstract factory model

Advantages of the Abstract factory model:

A Easy-to-exchange product line, because specific factory classes, such as Ifactoryfactory=new accessfactory (), need only occur once during initialization in an application, making it very easy to change the specific factory of an application, It only needs to change the specific factory to use different product configurations.

Our design is not going to prevent changes in demand, so our ideal is to make changes minimal, now if you want to change the database access, we only need to change the specific factory can do.

Two It separates the concrete creation process from the client, the client manipulates the instance through their abstract interface, and the specific class name of the product is separated from the implementation of the specific factory and will not appear in the customer code.

5.1.4 Data Access Program with Reflection + abstract factory

If we now add more access to Oracle, we need not only add a Oraclefactory factory class to the abstract factory, but also add a case to the switch method of the method of the data access class.

At this point, we can instantiate the corresponding database class based on the value of the string db. We need to use the reflective technology.

Using reflection technology, you first need to refer to the System.Reflection namespace, using reflection as follows:

Using System.Reflection;

Iuser result = (Iuser) assembly.load ("Abstract Factory mode"). CreateInstance;

Now we can move the program from compile time to run time, due to "CreateInstance (abstract Factory mode. The string in Sqlserveruser ") can be written as a variable, and the value of the variable is SQL Server, or access can be determined by the prior DB variable.

Modified data access classes are implemented using reflection technology instead of ifactory, Sqlserverfactory, and Accessfactory. The code is as follows:

Using System.Reflection;

Class DataAccess

{

private static readonly string Assemblyname= "abstract Factory mode";

private static readonly string db= "SQL Server";

public static Iuser CreateUser ()

{

String classname=assemblyname+ "." +db+ "User";

Return (Iuser) Assembly.Load (AssemblyName). CreateInstance (ClassName);

}

public static idepartment Createdepartment ()

{

String classname=assemblyname+ "." + "Department";

Return (ideparment) Assembly.Load (AssemblyName). CreateInstance (ClassName);

}

}

Now if we increase access to Oracle database, the increase of related classes is unavoidable, which can not be solved by any means, but this is called extension, open-closed principle tells us, for the expansion, we open. But for the modifications, we should try to close them. For the status quo, we need to change the "private static readonly string db=" SQL Server "to" private static readonly string db= "Oracle", i.e. (Iuser) Assembly.Load (AssemblyName). The CreateInstance (className) statement has changed.



Thus, Dataaccess.createuser () would have been given an example of Sqlserveruser, and now it has become an example of oracleuser.

If you need to increase the foodinfo, then increase the Foodinfo related three classes, and then modify

DataAccess, add a publicstatic Iproject Createfoodinfo () method in it. However, if you change the database, you have to modify the program (modify the value of the db) and recompile, is there a better way to solve the problem?

5.1.5 implementing data Access programs with Reflection + configuration files

For the previous section, we can use the configuration file to solve the problem. Add the app. Config file code as follows:

<?xml version= "1.0" encoding= "Utf-8"?>

<configuration>

<appSettings>

<add key= "DB" value= "SQL Server"/>

</appSettins>

</configuration>

On the project, right-click, manually add the reference system.configuration and add usingsystem.configuration at the beginning of the program, and then change the fields of the DataAccess class.

Private staticreadonly string db=configurationmanager.appsettings["db"];

So far, we have applied the Reflection + abstract factory pattern to solve the maintainable, extensible problem of database access.




C # 39 Abstract Factory mode

Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.