首页 > 代码库 > DesignPattern_Java:SingletonPattern
DesignPattern_Java:SingletonPattern
单例模式 SingletonPattern
Ensure a class has only one instance,and provide a global point of access to it.
单例模式的主要作用是确保一个类仅仅有一个实例存在。
懒汉式单例类:第一次引用类时,才进行对象实例化。
package com.DesignPattern.Creational.Singleton; public class Singleton_lHan { private static Singleton_lHan _instance = null; private Singleton_lHan() { } synchronized public static Singleton_lHan getInstance() { if (_instance == null) { _instance = new Singleton_lHan(); } return _instance; } }
饿汉式单例类:类载入时,就进行对象实例化。
package com.DesignPattern.Creational.Singleton; public class Singleton_eHan { private static Singleton_eHan m_instance = new Singleton_eHan(); private Singleton_eHan() { } public static Singleton_eHan getInstance() { return m_instance; } }
单例模式的实例
创建一个饿汉式单例类:GlobalNum.java
package com.DesignPattern.Creational.Singleton; public class GlobalNum { private static GlobalNum gn = new GlobalNum(); private int num = 0; public static GlobalNum getInstance() { return gn; } public synchronized int getNum() { return ++num; } }
SingleDemo.java
package com.DesignPattern.Creational.Singleton; public class SingleDemo { //測试单例模式 public static void main(String[] args) { //创建线程A NumThread threadA = new NumThread("thread A"); //创建线程B NumThread threadB = new NumThread("thread B"); //启动线程 threadA.start(); threadB.start(); } } //线程类 class NumThread extends Thread { private String threadName; public NumThread(String name) { threadName = name; } //重写线程的run方法(线程任务) public void run() { GlobalNum gnObj = GlobalNum.getInstance(); //循环訪问,输出訪问次数 for (int i = 0; i < 5; i++) { System.out.println(threadName + "第" + gnObj.getNum() + "次訪问!"); try { this.sleep(1000); //线程休眠1000毫秒 } catch (InterruptedException e) { e.printStackTrace(); } } } }
DesignPattern_Java:SingletonPattern
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。