重拾android路(十一) 设计模式

设计模式在Android中的应用

饿汉模式

1
2
3
4
5
6
7
public class {
private (){}
private static App app = new App();
public static App getApp(){
return app;
}
}

懒汉模式

1
2
3
4
5
6
7
8
9
10
public class {
private (){}
private static App app = null;
public static synchronized App getApp(){
if(app == null){
app = new App();
}
return app;
}
}

另外一种

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class {
private App(){}
private volatile static App app;
public static App getApp(){
if(app == null){
synchronized(App.class){
if(app == null){
app = new App();
}
}
}
return app;
}
}

静态内部类

1
2
3
4
5
6
7
8
9
public class App{
private static class GetAppInstance{
public static App mApp = new App();
}
private App(){}
public static App getApp(){
return GetAppInstance.mApp;
}
}