[Original-tutorial-serialization] "android big talk design mode"-design mode Creation Mode Chapter 4: Singleton Mode

Source: Internet
Author: User
<Big talk design model> description and copyright notice of this tutorial

L this document references and uses free images and content on the Internet, and is released in a free and open manner, hoping to contribute to the mobile Internet and the smart phone age! This document can be reproduced at will, but cannot be used for profit.

L if you have any questions or suggestions about this document, go to the official blog

Http://www.cnblogs.com/guoshiandroid/ (with the following contact information), we will carefully refer to your suggestions and modify this document as needed to benefit more developers!

L The latest and complete content of "big talk design mode" will be regularly updated on the official blog of guoshi studio. Please visit the blog of guoshi studio.

Http://www.cnblogs.com/guoshiandroid/get more updates.

Guoshi studio is a technical team dedicated to enterprise-level application development on the Android platform. It is committed to the best Android Application in China.ProgramDevelopment institutions provide the best Android enterprise application development training services.

Official contact information for Enterprise Training and Development Cooperation:

Tel: 18610086859

Email: hiheartfirst@gmail.com

QQ: 1740415547

QQ: 148325348

Guoshi studio is better for you!

 

 

  View other parts:Overall description and Chapter index of this tutorial

PDF download link

Singleton Mode You are my only 

Singleton ModeUse Cases: 

The phrase "you are my only one" is explained in the current language ".

Both Gg and mm are in love for the first time, and both regard each other as the only one in their own lives. In addition, GG and mm are constantly learning from each other and constantly improving themselves. The sweetness and happiness of GG and mm soon caused a sensation in the whole department. Boys generally take Gg's girlfriend to educate their girlfriends about how others are doing, while girls often take MM's boyfriend to say how boys should do it. In addition, the grade counselor praised Gg and mm at the grade meeting, saying that boys should want to learn from MM's boyfriend, and girls should learn from Gg's girlfriend! Well, obviously, everyone knows that the counselor said that Gg's girlfriend refers to mm, while MM's boyfriend refers to GG.

Singleton mode explanation: 

Gof defines Singleton pattern to ensure that only one class exists and a global access method can be used to access the instance.

The Singleton mode is an object creation mode. The Singleton mode ensures that only unique instance objects are generated for a class. That is to say, in the whole program space, the class only has one instance object.

The Singleton mode has three key points: one is that a class can only have one instance; the other is that it must create the instance on its own; and the third is that it must provide the instance to the entire system on its own.

Ensure a class only has one instance, and provide a global point of access to it.

Singleton ModeUMLFigure: 

The Singleton mode is simple, and its UML diagram is as follows:

In-depth analysis of Singleton Mode:

The Singleton mode has three key points: one is that a class can only have one instance; the other is that it must create the instance on its own; and the third is that it must provide the instance to the entire system on its own.

The Singleton mode is suitable for scenarios where a class has only one instance, such as window manager, print buffer pool, and file system. They are all prototype examples. Typically, objects of different types are accessed by different objects in a software system. Therefore, a global access pointer is required, which is a well-known Singleton mode application. Of course, this is only when you are sure that you no longer need any more instances.

In computer systems, resources to be managed include external software resources. For example, each computer may have several printers, but only one printer spooler can be used, this prevents two print jobs from being output to the printer at the same time. Each computer may have several HbA cards, but only one software should be responsible for managing the HBA card to avoid the situation where two fax jobs are simultaneously transferred to the HBA card. Each computer can have several communication ports. The system should centrally manage these communication ports to prevent a communication port from being simultaneously called by both requests.

Resources to be managed also include internal software resources. For example, most software has one or more properties files to store system configurations. Such a system should manage an attribute file by an object.

Internal software resources to be managed include components that are responsible for recording the number of visitors to the website, components that record internal events of the software system, components with error information, or components that check the system performance. These components must be centrally managed.

Use Case Analysis andCodeImplementation: 

In the above application scenario, no matter who is GG's girlfriend, everyone knows that only mm is used. Correspondingly, no matter who is talking about MM's boyfriend, everyone knows that GG is used. Both Gg and mm are examples of the other party's single-instance O (∩ _ ∩) O Haha ~

The UML Model diagram is as follows:

Here, I will explain the singleton mode by taking MM's boyfriend GG as an example.

In the first version of the GG Singleton mode, the GG object is instantiated immediately when the class is loaded. However, this method consumes computer resources. The specific implementation code is as follows:

PackageCom. diermeng. designpattern. Singleton;

/*

* The first version of GG Singleton mode is "Hungry Chinese"

*/

Public ClassGgversionone {

// Create a single Gg object when the class is loaded into the memory

Public Static FinalGgversiononeGgversionone=NewGgversionone ();

// Name attributes

PrivateString name;

 

 

PublicString getname (){

ReturnName;

}

 

Public VoidSetname (string name ){

This. Name = Name;

}

 

// Privatize the constructor

PrivateGgversionone (){

}

 

// Provides a global static method

Public StaticGgversionone getgg (){

Return Ggversionone;

}

}

The second version of GG Singleton mode: "lazy". It works well in a single thread, but there is a thread security problem in multiple threads. The Code is as follows:

PackageCom. diermeng. designpattern. Singleton;

/*

* The second version of the GG Singleton mode adopts the "lazy" mode to instantiate Gg only when needed.

*/

Public ClassGgversiontwo {

// Gg name

PrivateString name;

// Name referenced by the singleton itself

Private StaticGgversiontwoGgversiontwo;

 

PublicString getname (){

ReturnName;

}

 

Public VoidSetname (string name ){

This. Name = Name;

}

 

// Privatize the constructor

PrivateGgversiontwo (){

}

 

// Provides a global static method

Public StaticGgversiontwo getgg (){

If(Ggversiontwo=Null){

Ggversiontwo=NewGgversiontwo ();

}

Return Ggversiontwo;

}

}

The third version of GG Singleton mode adopts the function Synchronization Method to Solve the multithreading problem, but it is a waste of resources because the synchronization check is performed every time, the actual check is only the first time the instance is instantiated. The specific code is as follows:

PackageCom. diermeng. designpattern. Singleton;

/*

* The third version of GG Singleton mode synchronizes functions.

*/

Public ClassGgversionthree {

// Gg name

PrivateString name;

// Name referenced by the singleton itself

Private StaticGgversionthreeGgversionthree;

 

PublicString getname (){

ReturnName;

}

 

Public Void Setname(String name ){

This. Name = Name;

}

 

// Privatize the constructor

PrivateGgversionthree (){

}

 

// Provides a global static method using the synchronization method

Public Static SynchronizedGgversionthree getgg (){

If(Ggversionthree=Null){

Ggversionthree=NewGgversionthree ();

}

Return Ggversionthree;

}

}

In the fourth version of the GG Singleton mode, the solution not only solves the "lazy" multithreading problem, but also solves the waste of resources. It looks like a good choice. The specific code is as follows:

PackageCom. diermeng. designpattern. Singleton;

/*

* The fourth version of the GG Singleton mode not only solves the "lazy" multithreading problem, but also solves the waste of resources. It seems to be a good choice.

*/

Public ClassGgversionfour {

// Gg name

PrivateString name;

// Name referenced by the singleton itself

Private StaticGgversionfourGgversionfour;

 

PublicString getname (){

ReturnName;

}

 

Public VoidSetname (string name ){

This. Name = Name;

}

 

// Privatize the constructor

PrivateGgversionfour (){

}

 

// Provides a global static method

Public StaticGgversionfour getgg (){

If(Ggversionfour=Null){

Synchronized(Ggversionfour.Class){

If(Ggversionfour=Null){

Ggversionfour=NewGgversionfour ();

}

}

 

}

Return Ggversionfour;

}

}

Finally, create a test client to test version 4:

PackageCom. diermeng. designpattern. Singleton. client;

ImportCom. diermeng. designpattern. Singleton. ggversionfour;

 

/*

* Test the client

*/

Public ClassSingletontest {

Public Static VoidMain (string [] ARGs ){

// Instantiate

Ggversionfour gg1 = ggversionfour.Getgg();

Ggversionfour gg2 = ggversionfour.Getgg();

// Set the value

Gg1.setname ("ggalias ");

Gg2.setname ("GG ");

 

System.Out. Println (gg1.getname ());

System.Out. Println (gg2.getname ());

 

 

}

}

The output result is as follows:

Gg

Gg

 

Advantages and disadvantages of Singleton mode: 

Advantage: when the client uses a singleton instance, it only needs to call a single method to generate a unique instance, which is conducive to resource saving.

Disadvantages: first, the singleton mode is difficult to implement serialization, which makes it difficult for classes in singleton mode to be persistent, and of course it is difficult to transmit data over the network. Secondly, because Singleton adopts the static method, cannot be used in the inheritance structure. Finally, if multiple Java virtual machines exist in the distributed cluster environment, it is very difficult to determine which single instance is running.

Practical application of Singleton mode: 

The Singleton mode usually appears in the following situations: 

Sharing the same resource or operating the same object between multiple threads, such as the servlet Environment

Use global variables in the entire program space to share resources

In a large-scale system, the Creation Time of objects needs to be saved for performance consideration.

Tip: 

careful readers may find that the dual check mode in the writing Singleton mode uses the phrase "It looks like a good choice, the reason is that the Java thread's working sequence is uncertain, which will lead to the use of the thread without being instantiated in the case of multithreading, resulting in program crash. However, there is no problem with the double check in the C language. Because the master said: the double check is not true for the Java language. Even so, double check is still an ideal solution to solve the problem of multithreading.

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.