六.单例模式

1.定义

单例模式:确保一些类只存在一个实例,并提供全局访问点。如线程池等

2.实例

package designMode;

import java.io.IOException;

/**
 * 单例模式:确保一些类只存在一个实例,并提供全局访问点。如线程池等
 */
public class SinglePattern {
    public static void main(String[] args) throws IOException, InterruptedException {
        //由于构造器为private,外部无法调用
//        Singleton singleton = new Singleton();

        for (int i = 0; i < 3; i++) {
            Singleton instance = Singleton.getInstance();
        }
        System.out.println("");
        System.out.println("多线程单例模式");

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 5; i++) {
                    SingletonCunrent instance = SingletonCunrent.getInstance();
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 5; i++) {
                    SingletonCunrent instance = SingletonCunrent.getInstance();
                }
            }
        }).start();
    }
}

class Singleton {
    private static Singleton uniqueInstance;

    private Singleton() {
    }

    public static Singleton getInstance() {
        Integer i = 1;
        if (uniqueInstance == null) {
            uniqueInstance = new Singleton();
            i++;
        }
        System.out.print(i);
        return uniqueInstance;
    }
}

class SingletonCunrent {
    private volatile static SingletonCunrent uniqueInstance;

    private SingletonCunrent() {
    }

    public static SingletonCunrent getInstance() {
        Integer i = 1;
        if (uniqueInstance == null) {
            synchronized (SingletonCunrent.class) {
                if (uniqueInstance == null) {
                    uniqueInstance = new SingletonCunrent();
                }
            }
            i++;
        }
        System.out.print(i);
        return uniqueInstance;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 单例模式(SingletonPattern)一般被认为是最简单、最易理解的设计模式,也因为它的简洁易懂,是项目中最...
    成热了阅读 4,292评论 4 34
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,923评论 18 139
  • 前言 本文主要参考 那些年,我们一起写过的“单例模式”。 何为单例模式? 顾名思义,单例模式就是保证一个类仅有一个...
    tandeneck阅读 2,538评论 1 8
  • 清明寄哀思! 我回到了老家。祖父祖母的坟在村东的公墓群里,相依相偎在一起。祖父离开我们有十五年了,祖母离开我们也有...
    一声笑阅读 344评论 0 0
  • 好久了 得了一种深夜失眠 喜欢大半夜唱歌、写文章的病. 时常在深夜 看到自己一个人抱着吉他狂欢的身影 还有那些自由...
    却道故人心易变o_O阅读 314评论 1 2