三、单例模式

单例模式

**单例模式,大概意思我就自己讲下,就是不会重复new出新的对象。
	保证一个类仅有一个实例,并提供一个访问它的全局访问点**


	单例模式的Demo如下,简单的说下懒汉式:
package com.design.singleton;

/**
 * @author lei.zhang 
 */
public class Singleton {

    private static Singleton singleton = new Singleton();

    private Singleton() {

    }

    public static Singleton getInstance(){
        return singleton;
    }
}

上述代码就是单例模式代码,私有的构造方法导致不能new 对象,这样只能调用静态方法 getInstance,直接返回singleton,只会有一个对象。

客户端测试代码如下:

package com.design.singleton;

public class Client {

    public static void main(String[] args) {

        Singleton singleton1 = Singleton.getInstance();

        Singleton singleton2 = Singleton.getInstance();

        System.out.println(singleton1 == singleton2);

    }
}

输出结果为:True

2.接下来讲下,另外一种和饿汉式差不多,但是比简单的饿汉式demo更加安全,加锁。

package com.design.singleton;

/**
 * @author lei.zhang 
 */
public interface ProducerLogService {

    void SentMsgToKafka(String code);
}

接口ProducerLogService 的SentMsgToKafka方法

实现代码如下:

package com.design.singleton;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lei.zhang
 */
public class ProducerLogServiceImpl implements ProducerLogService {

    public ProducerLogServiceImpl(String code){

        List<String> lists = new ArrayList<>();
        lists.add(code);
    }


    @Override
    public void SentMsgToKafka(String code) {
        System.out.println("aaa");
    }
}

最重要的实现如下,单例,线程安全:

package com.design.singleton;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ProducerFactory {

    private static Map<String,ProducerLogService> producerLogServiceMap;

    private static volatile Lock lock = new ReentrantLock();

    public static ProducerLogService getProducer(String code){

        if(producerLogServiceMap == null){
            try{
                lock.lock();
                if(producerLogServiceMap == null) {
                    Map<String,ProducerLogService> tmp = new HashMap<>(16);
                    tmp.put("test", new ProducerLogServiceImpl("test"));
                    producerLogServiceMap = tmp;
                }
            }finally {
                lock.unlock();
            }
        }
        return producerLogServiceMap.get(code);
    }
}

加锁来限制单例,加两层判断也是绝对保证单例(多线程的情况下)

顺带讲下Spring下面的bean,默认为单例模式scope=“singleton”

<Bean id = ‘’ class = ‘’ init-method= ‘’ scope="singleton">

scope = “prototype” 为圆形,所以不是单例

<Bean id = ‘’ class = ‘’ init-method= ‘’ scope="prototype">

以前只是为个人的记录,如有错误可以留言和我讨论

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值