1.单例设计模式

单例设计模式

概念:

  单例模式是一种常见的设计模式多种,如懒汉、饿汉、登记式等

特点:

  • 1、单例类只能有一个实例
  • 2、单例类必须自己创建自己的唯一实例。
  • 3、单例类必须给所有其他对象提供这一实例。

饿汉式:

懒汉式一进内存就创建了实例

1 class Dog{
2     private Dog(){}
3     //内部定义一个实例,供内部调用
4     private static Dog d = new Dog();
5     //提供了一个访问该对象的方法。
6     public static Dog getDog(){
7         return d;
8     }
9 }

懒汉式:

饿汉式在调用它的get方法时才创建实例

1 class Cat{
2     private static Cat c = null;
3     
4     public static synchronized Cat getCat(){
5         if(c==null)
6             c = new Cat();
7         return c;
8     }
9 }
原文地址:https://www.cnblogs.com/gzc911/p/4955533.html