设计模式

程序员为了简便使用封装一些工具设计的模式

单例模式(饿汉)

无论是否使用 先创建出对象 耗费空间

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class  {
public static void main(String[] args) {
Util.getInstance().func();

}
}
class Util {

private Util(){};
//创建了唯一对象
private static Util instance = new Util();
//只能根据唯一的对象调用类中方法
public static Util getInstance(){
return instance;
}
public void func(){};
}

单例模式(懒汉)

调用时才加载 但是可能导致线程不同步

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Util {

private Util(){};
//创建了 **空**对象
private static Util instance = null;
//只能根据唯一的对象调用类中方法
public static Util getInstance(){
if(instance == null){
instance = new Util();
}
return instance;
}
public void func(){};
}

静态内部类(常用单例模式)

结合了上面两种模式 保证了线程安全

1
2
3
4
5
6
7
8
9
10
11
12
class Singleton{

private Singleton(){}

private static class SingletonInstance{
private static Singleton instance = new Singleton();
}

public static Singleton getInstance(){
return SingletonInstance.instance;
}
}

简单工厂方法(XXXfactory)

又叫做静态工厂方法(Static Factory Method)模式,但不属于23种GOF设计模式之一。简单工厂模式是由一个工厂对象决定创建出哪一种产品类的实例.百度百科

  1. 私有化构造方法
  2. 对外提供一个获取对象的方法 封装创建过程

异同

  • 异同点
    • 同: 私有化构造方法 提供返回对象的方法
    • 异: 对象实例不同 需要代码判断