单例模式:静态内部类
object Test51 {
val instance: Test51
get() = SingletonInstance.INSTANCE
private object SingletonInstance {
internal val INSTANCE: Test51 = Test51
}
}
//测试
fun main() {
var instance = Test51.instance
}
public class Test52 {
private Test52() {
}
private static class SingletonInstance {
private static final Test52 INSTANCE = new Test52();
}
public static Test52 getInstance() {
return SingletonInstance.INSTANCE;
}
//测试
public static void main(String[] args) {
Test52 instance = Test52.getInstance();
}
}
单例模式:双重检测
public class Test42 {
private static volatile Test42 singleton;
private Test42() {
}
public static Test42 getInstance() {
if (singleton == null) {
synchronized (Test42.class) {
if (singleton == null) {
singleton = new Test42();
}
}
}
return singleton;
}
public static void main(String[] args) {
Test42 instance = Test42.getInstance();
}
}
object Test41 {
@Volatile
private var singleton: Test41? = null
val instance: Test41?
get() {
if (singleton == null) {
synchronized(Test41::class.java) {
if (singleton == null) {
singleton = Test41
}
}
}
return singleton
}
}
fun main() {
val instance = Test41.instance
}
自定义view的构造方法对比:
public class MyJavaView extends View {
public MyJavaView(Context context) {
this(context, null);
}
public MyJavaView(Context context, AttributeSet attrs) {
this(context, attrs, -1);
}
public MyJavaView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public MyJavaView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
public static void main(String[] args) {
MyJavaView myJavaView1 = new MyJavaView(null);
MyJavaView myJavaView2 = new MyJavaView(null, null);
MyJavaView myJavaView3 = new MyJavaView(null, null, -1);
MyJavaView myJavaView4 = new MyJavaView(null, null, -1, -1);
}
}
class MyKotlinView1 : View {
constructor(ctx: Context?) :
this(ctx,null)
constructor(ctx: Context?, attrs: AttributeSet?) :
this(ctx,null,-1)
constructor(ctx: Context?, attrs: AttributeSet?, defStyleAttr: Int = -1) :
super(ctx, attrs, defStyleAttr)
}
class MyKotlinView2 @JvmOverloads constructor(
context: Context?,
attrs: AttributeSet? = null,
defStyleAttr: Int = -1
) : View(context, attrs, defStyleAttr) {
constructor(
context: Context?,
attrs: AttributeSet? = null,
defStyleAttr: Int = -1,
defStyleRes: Int = -1
) : this(context, attrs, defStyleAttr)
}
fun main() {
var myKotlinView11 = MyKotlinView1(null)
var myKotlinView12 = MyKotlinView1(null, null)
var myKotlinView13 = MyKotlinView1(null, null, -1)
var myKotlinView21 = MyKotlinView2(null)
var myKotlinView22 = MyKotlinView2(null, null)
var myKotlinView23 = MyKotlinView2(null, null, 1)
var myKotlinView24 = MyKotlinView2(null, null, 1, 2)
}