Grinding design mode-1

Source: Internet
Author: User
Document directory
  • 1.1 read the content of the configuration file
  • 1.2 non-use mode solution
  • 1.3 what's the problem?
  • 2.1 solution in singleton Mode
  • 2.2 schema structure and description
  • 2.3 Singleton mode sample code
  • 2.4 example of using Singleton mode for rewriting

Statement: Original Articles

 

Many of my friends are writing a single example. Although it is very simple, there are also many knowledge points in the single example to see if they can write something different.

 

 

Singleton)

 

1 Scenario problem 1.1 read Configuration File Content

Consider such an application to read the content of the configuration file.
Many application projects have application-related configuration files. These configuration files are mostly customized by the project developers and define the parameter data required by the application. Of course, in actual projects, such configuration files are mostly in xml format. The properties format is also used. After all, it is relatively simple to use Java to read configuration files in the properties format.
How can I read the content of the configuration file?

1.2 non-use mode solution

Some may think that it is not difficult to read the content of the configuration file directly, then, you can store the file content in the corresponding data object. Is it really that simple? First, let's take a look.
For the sake of simplicity, we assume that the system uses the properties format configuration file.
(1) Use Java to read the configuration file. The sample code is as follows:

/*** Read the application configuration file */public class AppConfig {/*** to store the value of parameter A in the configuration file */private String parameters; /*** is used to store the value of parameter B in the configuration file */private String parameterB; public String getParameterB () {return parameter;} public String getParameterB () {return parameterB ;} /*** constructor */public AppConfig () {// call readConfig () to read the configuration file;}/*** to read the configuration file, read the content in the configuration file and set it to the attribute */private void readConfig () {Properties p = new Properties (); InputStream in = null; try {in = AppConfig. class. getResourceAsStream ("AppConfig. properties "); p. load (in); // read the content in the configuration file and set it to the attribute. this. parametid = p. getProperty ("paramA"); this. parameterB = p. getProperty ("paramB");} catch (IOException e) {System. out. println ("An error occurred while loading the configuration file. The stack information is as follows:"); e. printStackTrace ();} finally {try {in. close ();} catch (IOException e) {e. printStackTrace ();}}}}

 

Note: Only the access parameter method is used.

(2) The application configuration file named AppConfig. properties is placed in the same package of AppConfig. A simple example is as follows:

paramA=aparamB=b

(3) Write a client to test it. The sample code is as follows:

Public class Client {public static void main (String [] args) {// create the object to read the application configuration AppConfig config = new AppConfig (); String paramA = config. getParameterA (); String paramB = config. getParameterB (); System. out. println ("paramA =" + paramA + ", paramB =" + paramB );}}

The running result is as follows:

paramA=a,paramB=b
1.3 what's the problem?

The above implementation is very simple. It is easy to implement the required functions. Do you have any questions?
Let's see where the client uses this class. It uses the new AppConfig instance to get an object that operates on the configuration file content. If the content of the configuration file is used in many places during system running, that is, the instance of the AppConfig object needs to be created in many places.
In other words, during system operation, there will be many AppConfig instance objects in the system. Is there any problem?
Of course there is a problem. Imagine that every AppConfig instance object contains the content of the configuration file. The system has multiple AppConfig instance objects, that is to say, the system will have multiple configuration files at the same time, which will seriously waste memory resources. If the content of the configuration file is small, the problem is still a little small. If the content of the configuration file is too large, the waste of system resources will be a big problem. In fact, for the AppConfig type, only one instance object is required during the runtime.
Abstract The above description further and the problem arises: During a system running, a class only needs one class instance. How can this problem be achieved?

2 solution 2.1 solution in singleton Mode

A reasonable solution for solving the above problems is the singleton mode. So what is the singleton mode?
(1) Singleton mode definition
Ensure that a class has only one instance and provides a global access point to it.
(2) how to solve the problem by using the singleton Mode
After carefully analyzing the problem above, a class can be created multiple instances. The root cause of the problem is that the class construction method is public, that is, you can create multiple instances by using the constructor to create external classes. In other words, as long as the class constructor can allow external access to the class, there is no way to control the number of instances for the class to be created externally.
To control the creation of only one instance for a class, the first problem is to revoke the permissions for creating the instance so that the class itself is responsible for the creation of its own class instance, then, this class provides external methods that can access this class instance. This is the implementation method of the singleton mode.

2.2 schema structure and description

The Singleton mode structure is shown in Figure 1:

Figure 1 Structure of Singleton Mode
Singleton:
Creates a unique instance of the Singleton class and provides a getInstance method to allow external access to the unique instance of the class.

2.3 Singleton mode sample code

In Java, the implementation of Singleton mode is divided into two types: lazy mode and ELE. Me mode, there are different implementation methods. The following shows the sample code for these two methods. The reason for writing this is detailed later.
(1) lazy implementation. The sample code is as follows:

/*** Example of lazy Singleton implementation */public class Singleton {/*** defines a variable to store the created class instance */private static Singleton uniqueInstance = null; /*** private constructor. Fortunately, the number of instances created is controlled internally */private Singleton () {//}/*** defines a method to provide a class instance for the client * @ return a Singleton instance */public static synchronized Singleton getInstance () {// determine whether the storage instance variable has a value if (uniqueInstance = null) {// if not, create a class instance, assign the value to the storage class instance's variable uniqueInstance = new Singleton ();} // if there is a value, use the return uniqueInstance;}/*** method directly, A singletonOperation instance can have its own operations */public void singletonOperation () {// function processing}/*** indicating properties. A singletonOperation instance can have its own properties */private String singletonData; /*** method to allow external users to access the attribute value * @ return attribute value */public String getSingletonData () {return singletonData ;}}

(2) Implementation of the hungry Chinese style. The sample code is as follows:

/*** Example of the implementation of a hungry Chinese Singleton */public class Singleton {/*** defines a variable to store the created class instance. You can create a class instance directly here, only one time */private static Singleton uniqueInstance = new Singleton ();/*** private constructor. Fortunately, the number of instances created is controlled internally */private Singleton () {//}/*** defines a method to provide a class instance for the client * @ return a Singleton instance */public static Singleton getInstance () {// directly use the created instance return uniqueInstance;}/*** method. A singletonOperation instance can have its own operations */public void singletonOperation () {// function processing}/*** indicating properties. A singletonData instance can have its own properties */private String singletonData;/*** indicating method, allow external users to access the attribute value through these methods * @ return attribute value */public String getSingletonData () {return singletonData ;}}
2.4 example of using Singleton mode for rewriting

You need to use the singleton mode to rewrite the example. Because Singleton mode has two implementation methods, you can choose one here to implement it. You can choose the hungry Chinese Implementation Method to rewrite the example.
The sample code for rewriting an instance using the hungry Chinese style is as follows:

/*** Read the application configuration file. The Singleton implementation */public class AppConfig {/*** defines a variable to store the created class instance. Create a class instance directly here, only once */private static AppConfig instance = new AppConfig (); /*** defines a method to provide the AppConfig class instance for the client * @ return an AppConfig instance */public static AppConfig getInstance () {return instance ;} /*** stores the value of parameter A in the configuration file */private String parameters;/*** stores the value of parameter B in the configuration file */private String parameterB; public String getParameterB () {return parameterB;}/*** privatized constructor */private AppConfig () {// call readConfig ();}/*** to read the configuration file and set the read content in the configuration file to the attribute */private void readConfig () {Properties p = new Properties (); InputStream in = null; try {in = AppConfig. class. getResourceAsStream ("AppConfig. properties "); p. load (in); // read the content in the configuration file and set it to the attribute. this. parametid = p. getProperty ("paramA"); this. parameterB = p. getProperty ("paramB");} catch (IOException e) {System. out. println ("An error occurred while loading the configuration file. The stack information is as follows:"); e. printStackTrace ();} finally {try {in. close ();} catch (IOException e) {e. printStackTrace ();}}}}

Of course, the test client also needs to change accordingly. The sample code is as follows:

Public class Client {public static void main (String [] args) {// create an object that reads the application configuration, AppConfig config = AppConfig. getInstance (); String paramA = config. getParameterA (); String paramB = config. getParameterB (); System. out. println ("paramA =" + paramA + ", paramB =" + paramB );}}

Test to see if the requirements can be met.

 

 

Coming soon

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.