An example of the advantages of Java interfaces and factory patterns

Source: Internet
Author: User
Tags abstract final insert interface mssql mysql return
With the popularization of the concept of the pattern, there are more and more programmers who understand the patterns and usage patterns, and many people have such a kind of doubt when they learn the mode: "Is it necessary to make it so complicated?" ”。 Indeed, because the tutorial's examples are too simplistic (and so convenient for readers to learn), or when the author chooses an example, it does not reflect the merits of the model, and in many cases it is too complicated to use the pattern only in the case of the problem. That leads to the misconception that "the pattern is to complicate simple problems?" ”。 Of course not, as you develop the practice of continuous enrichment, you will eventually find that the mode is powerful, and the model is not aristocratic programming way, it is a number of refined solutions to the problem of methodological skills.





through the learning model, programmers began to say goodbye to the past quasi-linear code, patterns expand our vision, strengthen our object-oriented programming thinking mode. But now there is another common problem, the blind application of the model. The pattern is the solution of the problem, the first problem is the model, the pattern is dependent on the problem to be solved. It is important to understand that patterns increase flexibility and reusability at the expense of increasing the complexity of the code in many cases. If using a pattern in your own code only increases the complexity of the code, while others have little or no flexibility and high reusability requirements, there is no need to give up more intuitive, simpler code for using patterns instead.





first-class master 90% focus on the problem of the solution, because a good solution is found, then the code is easy to write, and the code is simple and fluent, see such code is a kind of enjoyment and improvement; second-tier proficient 90% focuses on code implementation because the solution to the problem is not the best and the code for the implementation is more complex Three current rookie record water account, 90% of energy in knocking on the keyboard, often do most of the discovery does not work, back to use 90% of the time to knock on the keyboard, will not use any mode, write out the code only he can understand. Make the software is also fragmented, do a little change to have a lot of trouble, and you do not know what will happen after the changes, the feeling of living in a dangerous house.





Here's an example of a misuse pattern. I have been involved in a large group of the second phase of OA system development, the development of the original code architecture and add new functional modules. Very few documents I read the original code when it was in the code of the program to make the head as big as a bucket, and finally read: The original code architecture overall use of Factory mode, but also the most complex abstract factory model. It takes all module classes from factory to factory, and each module class has an interface, and each interface has only one module-real class, because it also uses proxy mode for permission control. After reading the code I began to embed the code, found that each new class, to six Java files to add the corresponding code, and in the class each add a method, but also to its interface and other four Java files to add the corresponding code. Oh, my God,!!!! Remember at that time my Wing refers to often do not listen to, is because the frequent use of CTRL + C, CTRL + V, Wing refers to the Ctrl key to tired. The whole project team is miserable, it's really annoying. At the end of the project I reviewed the following findings: Proxy mode is also used (there is now a new solution to the horizontal control of permissions such as AOP programming) but the factory model here is simply to gild the lily, not only does not solve what problem, but increase the code complexity and coupling, reduce the development efficiency even improve the maintenance difficulty. And that each class simply add an interface of the way, it is not reasonable, which makes me want to say that Stephen Chow said: "The ball ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ To start with, let's look at a common problem: a system needs to support multiple types of databases. People who have used databases such as Oracle and MSSQL know that their SQL is written in a different way. For example, Oracle's unique identification automatic + 1 field is a sequence, MSSQL changed the field properties became, there are a variety of unique SQL usage. In order to support multiple databases, do we need to develop multiple sets of systems? Of course No. See the solution below.





There are many kinds of database, we can abstract all the operation of the database in the system, write a combination of methods into a class, there are several databases we write several such classes. The specific design class diagram is as follows:














Brief Description:


oracledataoperate, Sqlserverdataoperate, Mysqldataoperate, respectively, representing Oracle, SQL Server, MySQL three kinds of database operation class. Inherit from Abstractdataoperate


Abstractdataoperate is an abstract class that contains methods of operation where different kinds of databases are the same code. Inherit from Dataoperate


Dataoperate is the uniform interface of the data manipulation class above, with only two methods: get a record and insert a record.


Dataoperatefactory is a factory method that unifies its methods to obtain instances of database operations classes.


SampleClass is the class of one of our system's functional modules.


people is an entity class that represents a record. Three field OID Unique identifier, name name, date birthday.





Detailed Description:


1, all system function module class only recognize Dataoperat this interface also does not have to control the specific implementation class is Oracledataoperate also sqlserverdataoperate. Dataoperate source code is as follows:


public interface Dataoperate {


//Take out a record based on the unique identification of the record


people getpeople (String OID);


//Insert a record


Boolean insertpeople (People people);


}





2, Abstractdataoperate, Oracledataoperate, Sqlserverdataoperate, Mysqldataoperate are inherited Dataoperate interface, there is nothing to say, omitted.





3, Dataoperatefactory. Let's see how the Factory method is written.


public class Dataoperatefactory {


public static final int ORACLE = 0; Defines three constants that represent a database type


public static final int MYSQL = 1;


public static final int SQL Server = 2;





private static Dataoperate db;


private static int dataType = MYSQL;


/**


* Obtains an instance of the database Operation class based on the database type (dataType),


* Here we use a single case pattern for dataoperate, because Oraceldataoperate is a stateless tool class,


* So the whole system can only keep one instance.


*


* @return Return is the interface, the client does not care about the specific implementation of the class


*/


public static Dataoperate getinstance () {


if (db = = null) {


if (DataType = = ORACLE)///returns the corresponding implementation class according to Datetype


return new Oraceldataoperate ();


if (DataType = = MYSQL)


return new Mysqldataoperate ();


if (dataType = SQL Server)


return new Sqlserverdataoperate ();


}


return DB;


}


}





4, the next step is to see how the usage end invokes the factory method and uses the data manipulation class.


/**


* System a function class


*/


public class SampleClass {


private Dataoperate db; Declare a database operation class, note that this is an interface. Oh


/** a method * *


public void SampleMethod () {


db = Dataoperatefactory.getinstance ();//Get a single instance


people p = db.getpeople ("123"); Get a record


db.insertpeople (P);/then plug it back in


}


}





we find that there is no shadow of Oraceldataoperate, mysqldataoperate, etc. in SampleClass, which is the power of the interface. Clients do not have to write different code for oraceldataoperate, it is only concerned about dataoperate, the specific to take the logic of that class by the dataoperatefactory responsible.





Summary:


from the example we can see what is the interface-oriented programming approach. SampleClass use of data manipulation classes can not be concerned with the specific class, as long as the interface is the line


want an instance? Only need to call Dataoperatefactory.getinstance (), the other hand in dataoperatefactory this factory to do it, use the end of nothing to care about.


we want to support the new database type, just like Oraceldataoperate, then write a class that inherits abstractdataoperate, such as Sysbasedataoperate. Then add the appropriate code to the dataoperatefactory.


If we want to be more configurable, you can set the value in the private static int dataType = MYSQL to a text file.


for the development of systems to support a variety of databases, strongly recommend the use of Hibernate, I now do the system is to use the hibernate, the development of MySQL, to the customer when the database changed DB2, the program does not make any changes, the real transplant. However, the method mentioned in this article is useless.











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.