Java language Implementation Structural design pattern-appearance mode

Source: Internet
Author: User

First, describe

Appearance mode is called the façade mode, is to a complex system of packaging, the system external interface unified by the appearance of the class provided. When a complex system needs to provide interfaces externally, it is necessary to uniformly encapsulate the externally available interface in an external system for use in a façade class. The most important feature of the appearance pattern is the wrapping of fine-grained objects into coarse-grained objects, which the application accesses to complete the invocation of the fine-grained object. In this way, the application can only see the appearance object, but not the specific object of detail, which will undoubtedly reduce the complexity of the application and improve the maintainability of the program.

In general, the appearance mode is a set of interfaces for the subsystem, which provides a unified interface, so that other systems access to the system through this unified interface to complete, the pattern is mainly composed of 3 parts: Abstract appearance class, the implementation of abstract appearance class concrete appearance class and other subsystem classes.


Second, the advantages and disadvantages of the appearance model

Advantages: The appearance mode reduces the dependence and complexity of the system by providing a unified external interface, which avoids the direct connection between the external system and the subsystem. The façade mode wraps complex, fine-grained object services into simple, easy-to-use coarse-grained functionality that facilitates client invocation (for example, Java API calls).

Disadvantage: Restricting the flexibility of class external systems to subsystem calls can only be called by the methods provided in the skin class.


Third, the source code

This case simulates Java using JDBC to connect to the database, data query and update operations, output query result set, release all resources in the database subsystem, we define the access interface to the external system through an abstract appearance class, and by two concrete appearance class implements the abstract appearance class, Provides a unified access interface to facilitate client access.

1. Subsystem class

Package Tong.day5_2.facade;import Java.io.file;import Java.io.fileinputstream;import java.util.properties;/** * Loads the config.properties database configuration file from the current project home directory, initializes the database configuration information */public class Confitginfo {private static String driver;private static  String url;private static string user;private static string password;public void Setconfig () {try {Properties Properties = New Properties (); File File = new file (System.getproperty ("User.dir") + "\\Config.properties");p roperties.load (new FileInputStream (file );d river = Properties.getproperty ("Databasedriver"); url = properties.getproperty ("Jdbcurl"); user = Properties.getproperty ("Databaseuser");p Assword = Properties.getproperty ("DatabasePassWord"); System.out.println ("Driver:" +driver+ ", url:" +url+ ", User:" +user+ ", Password:" +password ");} catch (Exception e) {e.printstacktrace (); SYSTEM.OUT.PRINTLN ("Configuration information initialization failed!") "); }} public static String Getdriver () {return driver;} public static void Setdriver (String driver) {confitginfo.driver = driver;} public static String GetUrl () {REturn URL;} public static void SetUrl (String url) {confitginfo.url = URL;} public static String GetUser () {return user;} public static void SetUser (String user) {confitginfo.user = user;} public static String GetPassword () {return password;} public static void SetPassword (String password) {confitginfo.password = password;}}

Package Tong.day5_2.facade;import Java.sql.connection;import Java.sql.drivermanager;import java.sql.ResultSet;  Import Java.sql.sqlexception;import java.sql.statement;/** * All functions related to database connection and operation * @author Tong * */public class DBConnection    {public Connection Connection;    Public Statement Statement;    Public ResultSet ResultSet; /** * CREATE DATABASE connection * @throws Exception */Public DBConnection () throws Exception {Class.forName (confitginfo.        Getdriver ());        Connection = Drivermanager.getconnection (Confitginfo.geturl (), Confitginfo.getuser (), Confitginfo.getpassword ());    statement = Connection.createstatement ();    }/** * Query database operation * * @param SQL SELECT statement * @return ResultSet Object * @throws Exception */        Public ResultSet Select (String sql) throws Exception {ResultSet = statement.executequery (sql);    return resultset; Public ResultSet Select (string table, string limit, int min, int max) throws SQLException {              String sql = "SELECT * from" (select A.*, ROWNUM rn from "+ table +" A where "+ Limit +") where RN <        = "+ Max +" and RN >= "+ min;        ResultSet = statement.executequery (SQL);    return resultset; /** * UPDATE Database operations * * @param SQL INSERT, delete,update statement * @throws Exception */Public Voi    d update (String sql) throws Exception {statement.execute (SQL); }public Connection getconnection () {return Connection;} public void SetConnection (Connection Connection) {this.connection = Connection;} Public Statement getstatement () {return Statement;} public void Setstatement (Statement Statement) {this.statement = Statement;} Public ResultSet Getresultset () {return ResultSet;}         public void Setresultset (ResultSet ResultSet) {this.resultset = ResultSet;} }

Package Tong.day5_2.facade;import java.sql.resultset;import java.sql.sqlexception;/** * Print output ResultSet result set * @author Tong * */public class Printresult {public    void Printresultset (ResultSet ResultSet) {    try {if (Resultset.next ()) { String  username = resultset.getstring ("username"); String  passwd = resultset.getstring ("passwd"); System.out.println ("Username:" +username+ ", Password:" +passwd);}} catch (SQLException e) {e.printstacktrace ();}}}
Package Tong.day5_2.facade;import Java.sql.connection;import Java.sql.resultset;import java.sql.SQLException; Import java.sql.statement;/** * Release database for all resources * @author Tong * */public class Releasedb {//Turn off Database resources: ResultSet, Statement, CO Nnection public    void Close (Connection connection,statement statement,resultset ResultSet) {        try {        if ( Resultset!=null) {        resultset.close ();}        if (statement!=null) {        statement.close ();}        if (connection!=null) {        connection.close ();}} catch (SQLException e) {e.printstacktrace ()}            }            }
2. Abstract appearance class

Package tong.day5_2.facade;//Abstract Appearance class, provides a unified interface for external systems, simplifies calling public interface facade {public abstract void dboperation ( String querysql);}

3 , the specific appearance of the class

Package Tong.day5_2.facade;import java.sql.resultset;/** * A specific appearance class that performs database query operations, primarily responsible for executing SELECT query statements and printing result sets * @author Tong * */ public class Dbselectfacade implements Facade{private confitginfo confitginfo;private DBConnection DBConnection; Private Printresult printresult;private releasedb releasedb;public dbselectfacade () {confitginfo = new confitgInfo (); try {//Get database connection and statementdbconnection = new DBConnection ();} catch (Exception e) {e.printstacktrace ();} Printresult = new Printresult (); releasedb = new Releasedb ();} Call the business method of the other class, provide to the client a most concise interface public void Dboperation (String querysql) {//Load database configuration file Initialize database configuration information confitginfo.setconfig () ;//Query data result resultSet ResultSet = null;; try {resultSet = Dbconnection.select (querysql);} catch (Exception e) {e.printstacktrace ();} Output data result set Printresult.printresultset (ResultSet);//Release all resources of the database Releasedb.close (Dbconnection.getconnection (), Dbconnection.getstatement (), Dbconnection.getresultset ());}}

Package Tong.day5_2.facade;import java.sql.resultset;/** * The specific appearance class that performs the database update operation, primarily responsible for executing the insert,delete,update UPDATE statement * @author Tong * */public class Dbupdatefacade implements Facade{private confitginfo confitginfo;private DBConnection DBConnection ;p rivate releasedb releasedb;public dbupdatefacade () {confitginfo = new confitginfo (); try {// Get database connection and statementdbconnection = new DBConnection ();} catch (Exception e) {e.printstacktrace ();} Releasedb = new Releasedb ();} Call the business method of the other class, provide to the client a most concise interface public void Dboperation (String querysql) {//Load database configuration file Initialize database configuration information confitginfo.setconfig () ;//execute INSERT, delete,update UPDATE statement try {dbconnection.update (querysql);} catch (Exception e) {e.printstacktrace ();} Frees all resources for the database Releasedb.close (Dbconnection.getconnection (), Dbconnection.getstatement (), Dbconnection.getresultset ());}}
4. Client Calls

Package tong.day5_2.facade;/** * The client test class can simply manipulate the database by invoking the appearance pattern class, and the design pattern masks a series of operations on the user's database. * Appearance mode the largest feature wraps fine-grained objects into coarse-grained objects, and the application accesses this skin object to complete the invocation of fine-grained objects. * We use the appearance of packaging, so that the application can only see the appearance of objects, but not to see the details of the object, this will undoubtedly reduce the complexity of the application and improve the maintainability of the program * @author Tong * */public class Facadetest {/** * @pa Ram args */public static void main (string[] args) {String sqlString = "Select Username,password from User"; String updatestring = "Update user set Username= ' Zhangsan ' where username= ' Lisi '";D bselectfacade dbusefacade = null;;D Bupdatefacade Dbupdatefacade = null;try {//Call query database for appearance class object to query data Dbusefacade = new Dbselectfacade (); Dbusefacade.dboperation (sqlString);//Call Update the Appearance class object of the database to update the data Dbupdatefacade = new Dbupdatefacade (); Dbupdatefacade.dboperation (updatestring);} catch (Exception E1) {e1.printstacktrace ();}}}

Iv. config.properties configuration files required to initialize the database

<span style= "FONT-SIZE:14PX;" >jdbcdriver=oracle.jdbc.driver.oracledriverjdbcurl=jdbc:oracle:thin:@192.168.1.230:1521:orcldatabaseuser= Systemdatabasepassword=tiger</span>





Java language Implementation Structural design pattern-appearance mode

Related Article

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.