-
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 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"); }}
Java Singleton mode