单例模式之懒汉模式&恶汉模式
2014-09-10 16:03
169 查看
单例模式,其实就是对于一个类,只能新建一个对象,不能有多个重复的对象。这样使得在程序在运行时,比如日志加载时能找到唯一的对象,以至正确匹配。就类似于一山不能有二虎一样。主要的思想其实就是运用static,在类内部new一个自己的对象,再通过类方法返回这个对象。由于静态方法new出的对象,故其实有着同样的hashCode,也即同一个对象。一下是代码:
Test.java
2.Singleton.java
3.Singleton2.java
懒汉模式和饿汉模式的取名也比较容易理解,因为懒汉模式在类加载时就已经new出了对象,这种模式new对象很着急,
而懒汉就你需要的时候再new,不紧不慢的。
Test.java
package com.demo_type; public class Test { public static void main(String[] args){ //饿汗模式 Singleton s1 = Singleton.getInstance(); Singleton s2 = Singleton.getInstance(); if(s1 == s2){ System.out.println("s1 = s2"); } else{ System.out.println("s1 != s2"); } //懒汉模式 Singleton2 s3 = Singleton2.getInstance(); Singleton2 s4 = Singleton2.getInstance(); if(s3 == s4){ System.out.println("s3 and s4 is the same"); } else{ System.out.println("s3 and s4 is NOT the same"); } } }
2.Singleton.java
package com.demo_type; /** * @author YBnew * 单例模式Singleton * 应用场合:有些对象只需要一个就足够了,如皇帝 * 作用: 保证整个应用程序中某个实例有且只有一个 */ public class Singleton { //1.将构造方法私有化,不允许外部直接创建对象 private Singleton(){ } //2.自己创建一个类的唯一实例 //3.将其便为static(如果将其设为private,更符合封装) private static Singleton instance = new Singleton(); public static Singleton getInstance(){ return instance; } }
3.Singleton2.java
package com.demo_type; /** * @author YBnew * 懒汉模式 * 区别: 饿汉模式的特点是加载类时比较慢,但运行是比较快-线程安全 * 懒汉模式的特点是加载类时比较快,但运行时比较慢-线程不安全 */ public class Singleton2 { //1.将构造函数私有化,不允许外部直接创建对象 private Singleton2(){ } //2.声明类的唯一实例,使用private static 修饰 private static Singleton2 instance; //3.判断一下,也即运行时加载 public static Singleton2 getInstance(){ // if(instance == null){ // return new Singleton2(); // } // else{ // return instance; // } if(instance == null){ instance = new Singleton2(); } return instance; } }
懒汉模式和饿汉模式的取名也比较容易理解,因为懒汉模式在类加载时就已经new出了对象,这种模式new对象很着急,
而懒汉就你需要的时候再new,不紧不慢的。
相关文章推荐
- JAVA单例设计模式简单实现(懒汉与恶汉),多例设计模式的简单实现
- 《转》单例模式中的懒汉模式和恶汉模式的区别
- 黑马程序员,黑马论坛-------单例模式的两种实现(恶汉+懒汉)
- 单例模式举例:恶汉模式,懒汉模式及其他
- 单例模式(懒汉与恶汉)
- java设计模式之单列模式(懒汉,恶汉,double-check- lock)
- iOS开发单例模式(懒汉模式&恶汉模式)
- java 单例模式 恶汉 懒汉 静态内部类 线程安全
- 单例模式中的懒汉模式和恶汉模式的区别
- 单例模式中的懒汉模式和饿汉模式
- 两种新建线程的简单方法以及懒汉模式中lock的重要性
- 设计模式-单例模式之懒汉模式
- 从java.lang.Runtime看单例懒汉饿汉模式的选择
- 懒汉 多线程 单例模式
- 懒汉模式与饿汉模式
- 单例模式——懒汉模式和饿汉模式
- 单例模式----懒汉+饿汉
- [黑马程序员]多线程_懒汉模式
- 从java.lang.Runtime看单例懒汉饿汉模式的选择
- 多线程下的懒汉模式,同步代码块和同步方法