设计模式--单例应用 java

最近有空闲时间,就想着把曾经用到过的设计模式做一个回顾,顺便也把它分享出来,仅供参考:

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();
        }

    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值