This article address: http://www.cnblogs.com/archimedes/p/java-singleton-pattern.html, reprint please indicate source address.
Single-Case mode
Ensure that a class has only one instance and provides a global access point to access it.
Overview
The singleton pattern is a mature pattern of how to design a class that has only one instance of the class, the key of which is to set the class's construction method to private permission and provide a class method that returns its only instance.
Applicability
1. When a class can have only one instance and the customer can access it from a well-known access point.
2. When this unique instance should be extensible by subclasses, and the customer should be able to use an extended instance without changing the code.
Participants
Singleton defines a instance operation that allows a client to access its only instance. Instance is a class operation. may be responsible for creating its own unique instance.
The structure and use of the singleton pattern
Only one role is included in the schema's structure:
• Single-piece Class (Singleton)
UML Class diagrams for schemas
Actual combat part
Description and use of the structure of the pattern
1. Singleton Class (Singleton): Moon.java
Public classMoon {Private StaticMoon Uniquemoon; Doubleradius; DoubleDistancetoearth; PrivateMoon () {Uniquemoon= This; Radius= 1738; Distancetoearth= 363300; } Public Static synchronizedMoon Getmoon () {if(Uniquemoon = =NULL) {Uniquemoon=NewMoon (); } returnUniquemoon; } Publicstring Show () {string S= "The radius of the Moon is" + radius + "km away from the earth is" + Distancetoearth + "km"; returns; }}
2. Application Application.java
Importjavax.swing.*;Importjava.awt.*; Public classApplication { Public Static voidMain (string[] args) {MyFrame F1=NewMyFrame ("Zhang San look at the moon"); MyFrame F2=NewMyFrame ("John Doe look at the moon"); F1.setbounds (10, 10, 360, 150); F2.setbounds (370, 10, 360, 150); F1.validate (); F2.validate (); }}classMyFrameextendsJFrame {String str; MyFrame (String title) {Settitle (title); Moon Moon=Moon.getmoon (); STR=moon.show (); Setdefaultcloseoperation (Jframe.dispose_on_close); SetVisible (true); Repaint (); } Public voidPaint (Graphics g) {Super. Paint (g); G.setfont (NewFont ("Arial", Font.Bold, 14)); g.DrawString (str,5, 100); }}
Advantages of Singleton mode
The only instance of a single-piece class is controlled by the single-piece class itself, so it's good to control when the user accesses it.
Java design mode 3--singleton mode (Singleton)