From 63473ed3e19a9d7f985de7c3d0f5bc675d75c23e Mon Sep 17 00:00:00 2001 From: YuCheng Hu Date: Wed, 21 Nov 2018 14:49:21 -0500 Subject: [PATCH] =?UTF-8?q?Java=20=E8=AE=BE=E8=AE=A1=E6=A8=A1=E5=BC=8F?= =?UTF-8?q?=E4=B8=AD=E7=9A=84=E5=8D=95=E4=BE=8B=E6=A8=A1=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../lang/tutorial/tests/SingletonTest.java | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 src/test/java/com/ossez/lang/tutorial/tests/SingletonTest.java diff --git a/src/test/java/com/ossez/lang/tutorial/tests/SingletonTest.java b/src/test/java/com/ossez/lang/tutorial/tests/SingletonTest.java new file mode 100644 index 0000000000..a6cd888777 --- /dev/null +++ b/src/test/java/com/ossez/lang/tutorial/tests/SingletonTest.java @@ -0,0 +1,69 @@ +package com.ossez.lang.tutorial.tests; + +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Eager Singleton + * + * @author YuCheng + * + */ +class EagerSingleton { + private static final EagerSingleton INSTANCE = new EagerSingleton(); + + // Private constructor suppresses + private EagerSingleton() { + } + + // default public constructor + public static EagerSingleton getInstance() { + return INSTANCE; + } +} + +/** + * Lazy Singleton + * + * @author YuCheng + * + */ +class LazySingleton { + private static volatile LazySingleton INSTANCE = null; + + // Private constructor suppresses + // default LazySingleton constructor + private LazySingleton() { + } + + // thread safe and performance promote + public static LazySingleton getInstance() { + if (INSTANCE == null) { + synchronized (LazySingleton.class) { + // when more than two threads run into the first null check same time, to avoid instanced more than one time, it needs to be + // checked again. + if (INSTANCE == null) { + INSTANCE = new LazySingleton(); + } + } + } + return INSTANCE; + } +} + +/** + * + * @author YuCheng + * + */ +public class SingletonTest { + private final static Logger logger = LoggerFactory.getLogger(SingletonTest.class); + + @Test + public void testSingleton() { + logger.debug("TEST Singleton"); + + } + +}