A singleton pattern in Java
-
The singleton pattern in Java is a common design pattern that requires only one instance of a class and provides a global access point to access his
Specific requirements:
I. Privatization of structural methods;
Second, declare a class of objects;
Third, provide a static method to the external, get the object instance
Two ways to achieve this:
1. A Hungry man type
First, create an instance,
class sington1{ private static sington1 s = New sington1 (); private sington1 () { } public static sington1 getinstance () { return s; } public void print () { system.out.println ("A Hungry man type singleton mode"); } }
2. Lazy Type
As the name implies: lazy, after creating an instance
Class sington2{private static Sington2 s =null; Private Sington2 () {} public static Sington2 getintance () {if (s==null) {s=new sington2 (); } return s; } void Print () {System.out.println ("lazy singleton mode"); }}
This article is from the "12260155" blog, please be sure to keep this source http://12270155.blog.51cto.com/12260155/1946160
A singleton pattern in Java