I. Real-world problems
Use ado.net in. NET to access the database. When reading data, you need to use a different data provider's Connection object, command object, adapter object, Data container object, and if the client needs to interact with these objects frequently when displaying the data, it adds to the complexity of the system and is not conducive to maintenance, just imagine if you need to get from the SQL The server database switches to Oracle, you need to modify the code that each data reads.
Two. The solution
Creates a "skin" for the data read operation that hides the details of the underlying data access that the client uses to read the required data.
A similar problem is the data validation that is often required on a Web page to determine whether the data is legitimate when submitting a form, or to change the appearance of the corresponding form element if it is not, and may use some regular expression objects or other objects when performing these operations. If you write in the normal way, it also adds to the complexity of the client. You can also use the skin mode at this point.
Three. Pattern definition
The purpose of the appearance mode (Façade) is to provide an interface through which a subsystem can be made easier to use.
Four. Sample code
Implement an application that displays all user names and product numbers, and before using skin mode, the class diagram looks like this:
After you introduce a skin for data access, the class diagram is as follows:
The Databasefacade class code looks like this:
class DatabaseFacade
{
public DataTable GetData(string sql)
{
using (SqlConnection conn = new SqlConnection(string.Empty))
{
DataTable table = new DataTable();
SqlDataAdapter ad = new SqlDataAdapter(string.Empty,conn);
ad.Fill(table);
return table;
}
}
}
The client accesses the data by its appearance:
class Client
{
public DataTable GetUserNames()
{
DatabaseFacade fac = new DatabaseFacade();
string sql = string.Empty;
DataTable table = fac.GetData(sql);
return table;
}
public DataTable GetProductIds()
{
DatabaseFacade fac = new DatabaseFacade();
string sql = string.Empty;
DataTable table = fac.GetData(sql);
return table;
}
}
Five. Model Summary
When you use the appearance pattern to hide details, you can more finely divide the details and place them in different classes or methods to provide a different look and make the client invocation easier.