Java Design Mode Creation Mode - Singleton

xiaoxiao2021-03-06  43

Singleton mode guarantees that only one example exists in a Java program. And provide a global access point access to it.

In many single-threaded occasions (establish a directory, database connection), etc.

Since Sinngleton is able to be status, the state factory will provide a status service to the outside if a plurality of monometic class come together.

In the case of a unique question (the number of records of the website, etc.), you can use a single state. And can add Synchroinzed security plus 1.

Singleton can also be in stateless, providing the nature of the tool. (I still don't understand, please master

Meconsea@hotmail.com)

Singleton limits the number of instances, which is conducive to the recovery of GC.

In the factory mode, it is also implemented in the Class Loader. Because the loaded Class is also a resource.

General Singleton has two modes:

First:

Public class singleletontest1 {

Private singletontest1 () {}

Private static singletontest1 singletonstance = new singleletontest1 ();

Public static singleletontest1 newinstance () {

Return Singletonstance;

}

}

SECOND:

Public class singletontest2 {

Private singletest2 () {}

Private static singleletontest2 newinstance = NULL;

Public static synchronized singletontest2 newinstance () {

/ / More efficient than first, because the instance only generates once

IF (newinstance == null) {

NEWINSTANCE = New Singletest2 ();

}

Return newinstance;

}

}

Sometimes in some cases, using Singleton does not reach the purpose of Singleton, if multiple Singleton objects are loaded simultaneously by different types of equipment; use in distributed systems such as EJB, pay attention to this situation, because EJB It is a cross server and cross JVM.

转载请注明原文地址:https://www.9cbs.com/read-67111.html

New Post(0)