An example showing the advantages of Java interfaces and factory models

Source: Internet
Author: User
With the popularization of the concept of patterns, there are more and more programmers who understand patterns and use patterns. Many people may have the following question when learning patterns: "Is it necessary to make it so complicated ?". Indeed, because the examples in the tutorial are too simple (so that readers can learn more easily), or the examples selected by the author do not reflect the advantages of the mode, in many cases, it is too complicated to use the mode. This leads to the misunderstanding that "is the mode to complicate simple problems ?". Of course not. As your development practices continue to enrich, you will eventually find that the mode is powerful, and the mode is not a noble programming method, it is some refined methods and techniques for solving the problem. Through the learning model, programmers began to say goodbye to the quasi-straight-line code method in the past. The model expanded our horizons and strengthened our way of thinking in object-oriented programming. However, there is another common problem: blind application mode. A mode is a solution to the problem. A mode is created only when there is a problem. A mode is dependent on the problem to be solved. It is necessary to understand that the mode enhances flexibility and reusability at the cost of improving Code complexity in many cases. If you use a certain mode in your own code only improves the complexity of the code, but other aspects have little effect, or some code does not have the need for flexibility and high reusability, therefore, we do not need to give up more intuitive and simple code writing for the use mode. A top-notch expert pays 90% attention to the problem solution. Because of the good solution, it is easy to write the code and the code is concise and fluent. It is a pleasure and improvement to look at this code; second-stream experts focus 90% on code implementation, because the solution to the problem is not the best, and the implementation code will be more complicated. Third-stream cainiao records the journal account, and 90% focus on the keyboard, it is often found that it does not work after more than half of the time. When I look back and use 90% of the time to press the keyboard, I will not use any mode. The code written can only be understood by myself. The software is also fragmented, and it will take a long time to make any changes, and you do not know what problems will occur after the changes, so you will feel like living in a dangerous room. Here is an example of misuse. I have participated in Phase II development of the OA system of a large group company. I have developed and used the original code architecture and added new functional modules. When I read the original code few times, the code in the program turned into a big fight. Finally, I understood that the original code architecture adopts the factory mode and is the most complex abstract factory mode. It generates all module classes and returns them to the factory through the factory. Each module class has an interface, and each interface has only one actual module class, this is because the proxy mode is used for permission control. After reading the code, I began to embed the code. I found that each new class requires the corresponding code to be added to six java files, and each method in the class is added, it also needs to add the corresponding code to its interface and other four java files. Day !!! I remember that at that time, my little finger often didn't listen, because I often used Ctrl + C, CTRL + V, and the little finger pressed the ctrl key to get tired. The entire project team is so miserable. After the project is over, I will review and find that the proxy mode is still in use (now there is a new solution for permission-based horizontal control with AOP programming). However, the factory mode is simply superfluous here, it not only does not solve any problems, but increases Code complexity and coupling, reducing development efficiency and increasing maintenance difficulty. In addition, the simple method of adding an interface to each class is even more unreasonable. This makes me want to say a sentence that Stephen Chow said: "ball ~~~ This is not the case ~~~~ Interfaces ~~~ This is not the case ~~~ ". Let's take a look at a common problem: a system needs to support multiple types of databases. Anyone who has used Oracle, MSSQL, and other databases knows that their SQL compiling methods are different. For example, if the unique identifier of Oracle is auto + 1, the field uses a sequence, and MSSQL changes the field attribute, there are various unique SQL usage. To support multiple databases, do we need to develop multiple systems? Of course no. See the solution below. As a matter of fact, there are many kinds of databases. We can abstract all the operations on the database in the system and write them into a class by combining methods. We can write several such classes for several databases. The specific design class diagram is as follows: Brief description:
  • Oracledataoperate, sqlserverdataoperate, and mysqldataoperate represent the operation classes of Oracle, sqlserver, and MySQL Databases respectively. Inherited from abstractdataoperate
  • Abstractdataoperate is an abstract class that contains operations that use the same code for different types of databases. Inherited from dataoperate
  • Dataoperate is the unified interface of the data operation class mentioned above. There are only two methods: getting a record and inserting a record.
  • Dataoperatefactory is a factory method that is used to obtain database operation instances.
  • Sampleclass is a class of a function module of our system.
  • People is an entity class that represents a record. The three fields are OID unique identifiers, name names, and date birthdays.
  Detailed description:1. All system function module classes only recognize dataoperat. The specific implementation class is oracledataoperate and sqlserverdataoperate. The source code of dataoperate is as follows: Public InterfaceDataoperate {// retrieve a record people getpeople (string OID) based on the unique identifier of the record; // insert a record BooleanInsertpeople (People people);} 2. abstractdataoperate, oracledataoperate, sqlserverdataoperate, and mysqldataoperate all inherit the dataoperate interface. There is nothing to say about it. 3. dataoperatefactory. Let's see how the factory method is written. Public ClassDataoperatefactory { Public Static Final IntOracle = 0; // define three constants representing the Database Type Public Static Final IntMySQL = 1; Public Static Final IntSqlserver = 2; Private StaticDataoperate dB; Private Static IntDatatype = MySQL;/*** obtain a database operation class instance based on the database type (datatype). * The single-instance mode is used for dataoperate, because oraceldataoperate and other tools are stateless, * The entire system only keeps one instance. ** @ ReturnThe returned interface does not need to be concerned with the specific implementation class */ Public StaticDataoperate getinstance (){ If(DB = Null){ If(Datatype = Oracle) // return the corresponding implementation Class Based on datetype Return NewCanceldataoperate (); If(Datatype = MySQL) Return NewMysqldataoperate (); If(Datatype = sqlserver) Return NewSqlserverdataoperate ();} ReturnDB ;}} 4. Next let's take a look at how the user end calls the factory method and uses the data operation class. /*** A function class of the system */ Public ClassSampleclass { PrivateDataoperate dB; // declare a database operation class. Note that the interface is used here. OH/** A Method */ Public VoidSamplemethod () {DB = dataoperatefactory. getinstance (); // get a single instance, people P = dB. getpeople ("123"); // get a record DB. insertpeople (p); // insert back} we found that sampleclass does not have any shadows such as canceldataoperate and mysqldataoperate, which is the power of the interface. The client does not have to write different code for canceldataoperate. It only cares about dataoperate. dataoperatefactory is responsible for the specific logic of the class. Summary:
  • In this example, we can see what is an interface-oriented programming method. Sampleclass you do not need to care about the specific class when using the data operation class, as long as it complies with the interface.
  • Want instance? You only need to call dataoperatefactory. getinstance (). Do it with the factory dataoperatefactory.
  • To support new database types, you only need to write a class that inherits abstractdataoperate, such as sysbasedataoperate, just like canceldataoperate. Then add the corresponding code to dataoperatefactory.
  • You can usePrivate Static IntThe value in datatype = MySQL; is set to a text file.
We strongly recommend that you use hibernate for developing systems that support multiple types of databases. Hibernate is used for the current system, MySQL is used for development, and DB2 is changed for the database to be provided to the customer, there is no need to make any changes to the program. 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.