设计模式_单例模式

回顾基础知识,温故而知新。

单例模式有饿汉模式和懒汉模式

 1 package com.xiaoysec.designpattern;
 2 /**
 3  * 
 4  * @author xiaoysec
 5  *本例是展示java单例模式中的饿汉模式
 6  *饿汉模式 特点:   类加载的速度比较慢(在类加载的过程中创建唯一的实例对象) 运行的速度会比较快 线程安全
 7  */
 8 
 9 public class Singleton {
10     //将构造方法定义为私有 防止外部创建新的实例对象
11    private Singleton(){}
12    
13    //private static修饰 在类加载时就创建唯一的实例对象 
14    private static Singleton instance = new Singleton();
15    
16    //public static修饰 外部调用以获取实例对象的引用
17    public static Singleton getInstance(){
18        return instance;
19    }
20     public static void main(String[] args){
21         Singleton instance = Singleton.getInstance();
22         Singleton instance2 = Singleton.getInstance();
23         if(instance == instance2){
24             System.out.println("是相同的对象");
25         }
26         else
27             System.out.println("不是相同的对象");
28     }
29 
30 }
View Code
 1 package com.xiaoysec.designpattern;
 2 /**
 3  * 
 4  * @author xiaoysec
 5  *本例主要展示java单例模式中的懒汉模式
 6  *懒汉模式的特点是  在类加载是并不创建实例对象 类加载的速度比较快但是运行的速度会比较慢(对象创建)线程不安全
 7  */
 8 public class Singleton2 {
 9     private Singleton2(){}
10     
11     
12     private static Singleton2 instance = null;
13     
14     
15     public static Singleton2 getInstance(){
16         if(instance==null){
17             instance = new Singleton2();
18         }
19         return instance;
20     }
21     public static void main(String[] args){
22         Singleton2 instance1 = Singleton2.getInstance();
23         Singleton2 instance2 = Singleton2.getInstance();
24         if(instance1 == instance2){
25             System.out.println("是同一个对象");
26         }else
27             System.out.println("不是同一个对象");
28     }
29 
30 }
View Code
原文地址:https://www.cnblogs.com/xiaoysec/p/4269026.html