Java第十天-单例设计模式

单例设计模式:

1.解决的问题,使得一个类只能够创建一个对象,

2.如何实现:

饿汉式
    	// 1.私有构造器:使得在类外部不能调用构造器
	
	private Singleton() {

	}
	// 2.自己在类内部创建一个类的实例
  private static Singleton instance = new Singleton();
	// 3.私有化此对象,通过公共的方法来调用
  
  public static Singleton getInstance(){
	  return instance;
  }
     //4.此公共的方法:只能通过类来调用,所以设置为 static的,同时类的实例也必须为static声明的

懒汉式
	// 1.私有构造器:使得在类外部不能调用构造器
	private Singleton1() {

	}
	// 2.自己在类内部创建一个类的实例
  private static Singleton1 instance = null;
	// 3.私有化此对象,通过公共的方法来调用
  
  public static Singleton1 getInstance(){
	  if(instance == null){
		  instance = new Singleton1();
	  }
	  return instance;
  }
     //4.此公共的方法:只能通过类来调用,所以设置为 static的,同时类的实例也必须为static声明的

区别在于:懒汉式,假如没有类调用这个类,那么instance就不会被创建,当有类需要调用的时候再创建。而
饿汉式已经提前给你创建好了这个instance,所以直接就return。
懒汉式可能出现线程安全问题

猜你喜欢

转载自blog.csdn.net/qq_34343249/article/details/84995014