码迷,mamicode.com
首页 > 其他好文 > 详细

单例设计模式

时间:2018-08-31 23:26:07      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:tor   pre   turn   str   安全   tin   外部   方法   饿汉式   

单例设计模式:一个类只能创建一个对象。

实现思路:

1、私有化构造器,使得类的外部不能调用此构造器

2、在类的内部创建一个类的实例

3、私有化对象,通过公共的方法来调用

4、此公共的方法,只能通过类来调用,因此是静态的,类的实例也是静态的

/**
 * 饿汉式
 * @author Administrator
 *
 */
class Singleton{
	 private Singleton(){
		 
	 }
	 
	 private static Singleton instance =new Singleton();
	 
	 public static Singleton getInstance(){
		 return instance;
	 }
}

/**
 * 懒汉式 调用时才创建 有线程安全问题
 * @author Administrator
 *
 */
class Singleton1{
	private Singleton1(){
		
	}
	
   private static Singleton1 instance =null;
   
   public static Singleton1 getInstance(){
	   if(instance ==null){
		   instance=new Singleton1();
	   }
	   return instance;
   }
}

  

单例设计模式

标签:tor   pre   turn   str   安全   tin   外部   方法   饿汉式   

原文地址:https://www.cnblogs.com/learningkeeper/p/9568599.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!