懒汉模式

  1. public class Demo2 {
  2. private static Demo1 demo = null;
  3. public Demo2() {
  4. }
  5. private static Demo1 getInstance() {
  6. if (demo == null) {
  7. synchronized (Demo2.class) {
  8. if (demo == null) {
  9. demo = new Demo1();
  10. }
  11. }
  12. }
  13. return demo;
  14. }
  15. }

饿汉模式

  1. public class Demo3 {
  2. public Demo3() {
  3. }
  4. private static Demo1 demo = new Demo1();
  5. private static Demo1 getInstance() {
  6. return demo;
  7. }
  8. }

静态内部类模式

  1. public class Demo4 {
  2. public Demo4() {
  3. }
  4. private static class DemoHolder {
  5. private static final Demo1 DEMO = new Demo1();
  6. }
  7. private static Demo1 getInstance() {
  8. return DemoHolder.DEMO;
  9. }
  10. }

枚举模式

  1. public class Demo5 {
  2. public static void main(String[] args) {
  3. DemoEnum.DEMO.getDemo();
  4. }
  5. public enum DemoEnum {
  6. DEMO;
  7. private Demo1 demo;
  8. public Demo1 getDemo() {
  9. return demo;
  10. }
  11. DemoEnum() {
  12. this.demo = new Demo1();
  13. System.out.println("111");
  14. }
  15. }
  16. }