Design Pattern 12-proxy (Structural)

Source: Internet
Author: User
1. Scenario Simulation

Consider such a practical application:
HR suggested that when selecting a department or branch, employees under all branches should be displayed without turning pages to facilitate business processing. Only the name should be displayed, however, clicking the name will display the details of the employee.
2. solution without Mode

The database code will not be written. In general, it is the user table and department table.
Directly add Java code
2. 1. Object describing user data

Package demo10.proxy. example1;/*** object describing user data */public class usermodel {/*** user ID */private string userid; /*** user name */private string name;/*** department ID */private string depid;/*** Gender */private string sex; Public String getuserid () {return userid;} public void setuserid (string userid) {This. userid = userid;} Public String getname () {return name;} public void setname (string name) {This. name = Name;} Public String getdepid () {return depid;} public void setdepid (string depid) {This. depid = depid;} Public String getsex () {return sex;} public void setsex (string sex) {This. sex = sex ;}@ overridepublic string tostring () {return "userid =" + userid + ", name =" + name + ", depid =" + depid + ", sex = "+ sex +" \ n ";}}
2. Implement the functions required by the example
Package demo10.proxy. example1; import Java. SQL. connection; import Java. SQL. drivermanager; import Java. SQL. preparedstatement; import Java. SQL. resultset; import Java. util. arraylist; import Java. util. collection; /*** implement the functions required by the example */public class usermanager {/*** obtain all personnel in the department according to the department ID ** @ Param depid * Department ID *@ return all persons in the Department */public collection <usermodel> getuserbydepid (string depid) throws exception {collecti On <usermodel> Col = new arraylist <usermodel> (); connection conn = NULL; try {conn = This. getconnection (); string SQL = "select * From tbl_user U, tbl_dep D" + "where u. depid = D. depid and D. depid like? "; Preparedstatement pstmt = Conn. preparestatement (SQL); pstmt. setstring (1, depid + "%"); resultset rs = pstmt.exe cutequery (); While (RS. next () {usermodel um = new usermodel (); um. setuserid (RS. getstring ("userid"); um. setname (RS. getstring ("name"); um. setdepid (RS. getstring ("depid"); um. setsex (RS. getstring ("sex"); Col. add (UM);} Rs. close (); pstmt. close ();} finally {Conn. close ();} return Col;}/*** obtain the connection to the database ** @ return database connection */private connection getconnection () throws exception {class. forname ("oracle. JDBC. driver. oracledriver "); Return drivermanager. getconnection ("JDBC: oracle: thin :@ localhost: 1521: orcl", "test", "test ");}}
2. 3. Client
package demo10.proxy.example1;import java.util.*;public class Client {public static void main(String[] args) throws Exception{UserManager userManager = new UserManager();Collection<UserModel> col = userManager.getUserByDepId("0101");System.out.println(col);}}
3. Problem

When the number of data entries Accessed at one time is too large and the data volume of each data entry is large, the memory will be consumed. How can this problem be solved?
4. Thinking about Using proxy mode to solve 4.1 Problems

In fact, it is very simple. At the beginning, we only need to display the name and click the name to enter the details. Therefore, we can add a proxy between them, specifically responsible for controlling the access to a piece of data. After clicking the name, you can query the database again. In fact, it is a policy to change the time to space.
4.2 structure and description of proxy Mode

4.3 Sample Code of proxy Mode
Package demo10.proxy. example2;/*** abstract target interface, which defines the specific target object and the Public proxy interface */public interface subject {/*** method: an abstract Request Method */Public void request ();} package demo10.proxy. example2;/*** specific target object, which is the real proxy object */public class realsubject implements subject {public void request () {// execute specific function processing} package demo10.proxy. example2;/*** proxy object */public class proxy implements subject {/*** hold the specific target object of the proxy */private realsubject = NULL; /*** constructor to pass in the specific target object of the proxy * @ Param realsubject specific target object of the proxy */Public proxy (realsubject) {This. realsubject = realsubject;} public void request () {// You can execute some functions before calling a specific target object. // you can call the realsubject method of a specific target object. request (); // some functions can be executed after the target object is transferred }}
5. Use proxy mode to override Example 5.1 interface for defining user data objects
Package demo10.proxy. example3;/*** interface for defining user data objects */public interface usermodelapi {Public String getuserid (); Public void setuserid (string userid); Public String getname (); public void setname (string name); Public String getdepid (); Public void setdepid (string depid); Public String getsex (); Public void setsex (string sex );}
5.2 There is no change in the object describing user data
Package demo10.proxy. example3;/*** object describing user data */public class usermodel implements usermodelapi {/*** user ID */private string userid; /*** user name */private string name;/*** department ID */private string depid;/*** Gender */private string sex; Public String getuserid () {return userid;} public void setuserid (string userid) {This. userid = userid;} Public String getname () {return name;} public void setname (string name) {This. name = Name;} Public String getdepid () {return depid;} public void setdepid (string depid) {This. depid = depid;} Public String getsex () {return sex;} public void setsex (string sex) {This. sex = sex ;}@ overridepublic string tostring () {return "userid =" + userid + ", name =" + name + ", depid =" + depid + ", sex = "+ sex +" \ n ";}}
5.3 proxy object: proxy User Data Object
Package demo10.proxy. example3; import Java. SQL. connection; import Java. SQL. drivermanager; import Java. SQL. preparedstatement; import Java. SQL. resultset; import Java. SQL. sqlexception;/*** proxy object, proxy user data object */public class proxy implements usermodelapi {/*** holds the specific target object of the proxy */private usermodel realsubject = NULL;/*** constructor, pass in the specific target object of the proxy ** @ Param realsubject * specific target object of the proxy */Public proxy (usermodel realsubject) {This. realsubject = realsubject;}/*** indicates whether data has been reloaded */private Boolean loaded = false; Public String getuserid () {return realsubject. getuserid ();} public void setuserid (string userid) {realsubject. setuserid (userid);} Public String getname () {return realsubject. getname ();} public void setname (string name) {realsubject. setname (name);} public void setdepid (string depid) {realsubject. setdepid (depid);} Publ IC void setsex (string sex) {realsubject. setsex (sex);} Public String getdepid () {// you need to determine whether the IF (! This. loaded) {// reload () from the database; // set the reload flag to truethis. loaded = true;} return realsubject. getdepid ();} Public String getsex () {If (! This. loaded) {reload (); this. loaded = true;} return realsubject. getsex ();}/*** re-query the database to obtain complete user data */private void reload () {system. out. println ("re-query the database to obtain complete user data, userid =" + realsubject. getuserid (); connection conn = NULL; try {conn = This. getconnection (); string SQL = "select * From tbl_user where userid =? "; Preparedstatement pstmt = Conn. preparestatement (SQL); pstmt. setstring (1, realsubject. getuserid (); resultset rs = pstmt.exe cutequery (); If (RS. next () {// you only need to obtain the realsubject data except userid and name again. setdepid (RS. getstring ("depid"); realsubject. setsex (RS. getstring ("sex");} Rs. close (); pstmt. close ();} catch (exception ERR) {err. printstacktrace ();} finally {try {Conn. close ();} catch (sqlexception e) {e. printstacktrace () ;}} Public String tostring () {return "userid =" + getuserid () + ", name =" + getname () + ", depid = "+ getdepid () +", sex = "+ getsex () +" \ n ";} private connection getconnection () throws exception {class. forname ("oracle. JDBC. driver. oracledriver "); Return drivermanager. getconnection ("JDBC: oracle: thin :@ localhost: 1521: orcl", "test", "test ");}}
5.4 implement the functions required by the example
Package demo10.proxy. example3; import Java. SQL. connection; import Java. SQL. drivermanager; import Java. SQL. preparedstatement; import Java. SQL. resultset; import Java. util. arraylist; import Java. util. collection; /*** implement the functions required by the example */public class usermanager {/*** obtain all personnel in the department according to the department ID ** @ Param depid * Department ID *@ return all persons in the Department */public collection <usermodelapi> getuserbydepid (string depid) throws exception {colle Ction <usermodelapi> Col = new arraylist <usermodelapi> (); connection conn = NULL; try {conn = This. getconnection (); // The string SQL = "select U. userid, U. name "+" from tbl_user U, tbl_dep D "+" where u. depid = D. depid and D. depid like? "; Preparedstatement pstmt = Conn. preparestatement (SQL); pstmt. setstring (1, depid + "%"); resultset rs = pstmt.exe cutequery (); While (RS. next () {// here is the created proxy object, instead of directly creating the usermodel object proxy = new proxy (New usermodel ()); // you can set the userid and name values for proxy. setuserid (RS. getstring ("userid"); proxy. setname (RS. getstring ("name"); Col. add (proxy);} Rs. close (); pstmt. close ();} finally {Conn. close ();} return Col;}/*** obtain the connection to the database ** @ return database connection */private connection getconnection () throws exception {class. forname ("oracle. JDBC. driver. oracledriver "); Return drivermanager. getconnection ("JDBC: oracle: thin :@ localhost: 1521: orcl", "test", "test ");}}
5.5 client Test
Package demo10.proxy. example3; import Java. util. *; public class client {public static void main (string [] ARGs) throws exception {usermanager = new usermanager (); collection <usermodelapi> Col = usermanager. getuserbydepid ("0101"); // if only the user name is displayed, you do not need to re-query the database for (usermodelapi umapi: COL) {system. out. println ("User ID: =" + umapi. getuserid () + ", User name: =" + umapi. getname ();} // If you access attributes other than the user ID and user name, the database for (usermodelapi umapi: COL) {system. out. println ("User ID: =" + umapi. getuserid () + ", User name: =" + umapi. getname () + ", Department: =" + umapi. getdepid ());}}}
6. Mode description 6.1 understanding proxy Mode

In proxy mode, a proxy object is created to represent a real object. After the client obtains this object, it has no effect on the client, just like obtaining a real object. When the client operates on this proxy object, the function is actually completed by the real object, but only by the proxy, that is, the client operates on the proxy and the proxy operates on the real object.
6.2 proxy mode call

 
6.3 think proxy Mode

The essence of the proxy mode is to control object access.
In proxy mode, the proxy object and the target object are inserted between the client and the target object, so as to introduce some indirect information between the client and the target object. This mode is applicable when a certain object is queried for a small number of times. Otherwise, it will be queried as many as n + 1 times.

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.