设计模式前年就涉及一些了,不过一直没怎么总结,写一系列博客总结下自己知道的几个。
首先是单例模式
单例模式的重点有下面几点:
1.类的构造方法设为私有
2.使用静态函数返回实例的引用
3。因为静态方法只能访问静态field,所以该单例的引用也要为static
4. 注意多线程下的安全性
第一种实现如下:
package com.test.singleton;
public class SingletonTest {
public static void main(String[] args) {
Singleton singleton1 = Singleton.getInstance();
Singleton singleton2 = Singleton.getInstance();
System.out.println(singleton1 == singleton2);
}
}
class Singleton
{
private static Singleton singleton = new Singleton();
private Singleton()
{
}
public static Singleton getInstance()
{
return singleton;
}
}
第二种可以这样写:
package com.test.singleton;
public class SingletonTest {
public static void main(String[] args) {
Singleton singleton1 = Singleton.getInstance();
Singleton singleton2 = Singleton.getInstance();
System.out.println(singleton1 == singleton2);
}
}
class Singleton
{
private static Singleton singleton = null;
private Singleton()
{
}
public static Singleton getInstance()
{
if (singleton == null)
singleton = new Singleton();
return singleton;
}
}
显然学过多线程的都知道这段代码不安全,剩下的有时间更新。
有时间加上C++版。