最近有空闲时间,就想着把曾经用到过的设计模式做一个回顾,顺便也把它分享出来,仅供参考:
1、创建单例类
import org.apache.camel.CamelContext;
import org.apache.camel.impl.DefaultCamelContext;
/**
* Created by LK on 2016/5/7.
*/
public class Singleton {
/**
* 一个静态的实例
*/
private static Singleton singleton;
private static CamelContext camelContext;
/**
* 私有化构造函数
*/
private Singleton(){
}
/**
* 给出一个公共的静态方法返回一个单一实例
* @return
*/
public static Singleton getInstance(){
if(singleton == null){
synchronized (Singleton.class){
if(singleton == null){
singleton = new Singleton();
System.out.println("xxxx");
}
}
}
System.out.println("yyyy");
return singleton;
}
public CamelContext getCamelContext(){
if(camelContext == null){
synchronized (Singleton.class){
if(camelContext == null){
camelContext = new DefaultCamelContext();
System.out.println("context1");
}
}
}
System.out.println("context2");
return camelContext;
}
}
2、一个测试main
import org.apache.camel.CamelContext;
/**
* Created by LK on 2016/5/7.
*/
public class UseSingleton {
public static void main(String[] args) {
for(int index=0;index<5;index++){
new Thread(){
public void run(){
while (true){
Singleton singleton = Singleton.getInstance();
CamelContext camelContext = singleton.getCamelContext();
//System.out.println(camelContext.getName());
}
}
}.start();
}
}
}