前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >剑指officer第二题:题目:设计一个类,我们只能生成该类的一个实例(五种方法实现)

剑指officer第二题:题目:设计一个类,我们只能生成该类的一个实例(五种方法实现)

作者头像
粲然忧生
发布2022-08-02 14:54:18
2610
发布2022-08-02 14:54:18
举报
文章被收录于专栏:工程师的分享
代码语言:javascript
复制
package learn;

public class offer1 {
	/*
	 * 单例模式:懒汉模式、饱汉模式,线程安全,但由于不论使用与否都会创建实例,造成了资源浪费
	 */
	public static class singleton {

		private final static singleton instance = new singleton();

		public static singleton getInstance() {
			return instance;
		}

		private singleton() {
		}

	}
	/*
	 * 单例模式:懒汉模式、饱汉模式,使用内部静态类,【比较推荐】虽然见到的不多,笔者也是参考了其他文章才写出来 静态内部类可以改编为静态代码快
	 */
	public static class singleton2{
		private final static class instanceFactory{
			private final static singleton2 instance = new singleton2();
		}
			
		public static singleton2 getInstance(){
			return instanceFactory.instance;
		}
		
		
		private singleton2(){
		}
		
	}
	

	/*
	 * 单例模式:饥汉模式,相对懒汉模式,资源使用时才会创建,但线程不安全,
	 */
	public static class singleton3 {
		private static singleton3 instance = null;

		private static singleton3 getInstance() {
			if (instance == null) {
				instance = new singleton3();
			}
			return instance;
		}

		private singleton3() {
		}
	}

	/*
	 *   单例模式:饥汉模式,相对懒汉模式,线程安全,但多线程效率不高
	 * */
	public static class singleton4{
		private static singleton4 instance = null;
		
		public synchronized static singleton4 getInstance(){
			if(instance == null){
				instance = new singleton4();
			}
			return instance;
		}
		
		private singleton4(){
		}
	}
	
	/*
	 *   单例模式:饥汉模式,双校验模式,相对懒汉模式,线程安全,效率较高【推荐】相对来说最后一种比较常见,也是对同步的考虑较多
	 * */
	public static class singleton5{
		private static singleton5 instance = null;
		
		public static singleton5 getInstance(){
			if(instance == null){
				synchronized (singleton5.class){
					if(instance ==null){
						instance = new singleton5();
					}
				}
			}
			return instance;
		}
		
		private singleton5(){	
		}
		
	}
	
	public static void main(String[] args) {
		System.out.println(singleton.getInstance()==singleton.getInstance());
		System.out.println(singleton2.getInstance()==singleton2.getInstance());
		System.out.println(singleton3.getInstance()==singleton3.getInstance());
		System.out.println(singleton4.getInstance()==singleton4.getInstance());
		System.out.println(singleton5.getInstance()==singleton5.getInstance());
	}
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2015-07-15,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档