博客
关于我
2-单例模式 - 创建型模式
阅读量:399 次
发布时间:2019-03-05

本文共 953 字,大约阅读时间需要 3 分钟。

文章目录

参考:设计模式之禅,https://www.runoob.com/

1. 例子

在这里插入图片描述

public class SingleObject {       private static SingleObject instance = new SingleObject();    private SingleObject() {       }    public static SingleObject getInstance() {           return instance;    }    public void showMessage() {           System.out.println(instance);    }}
public class SingletonPatternDemo {       public static void main(String[] args) {           for (int i = 0; i < 3; i++) {               SingleObject instance = SingleObject.getInstance();            instance.showMessage();        }    }}

输出结果是一样的,表明是同个对象。

com.freedom.pattern.singleton.SingleObject@47089e5fcom.freedom.pattern.singleton.SingleObject@47089e5fcom.freedom.pattern.singleton.SingleObject@47089e5f

2. 单例模式特点

  • 只有一个实例;
  • 构造函数必须私有,即其他对象不能通过new创建;
  • 自身必须提供获得实例的方法。

3. 延伸阅读

  • https://www.runoob.com/design-pattern/singleton-pattern.html
  • https://design-patterns.readthedocs.io/zh_CN/latest/creational_patterns/singleton.html

转载地址:http://tphwz.baihongyu.com/

你可能感兴趣的文章
mysql优化--索引原理
查看>>
MySQL优化之BTree索引使用规则
查看>>
MySQL优化之推荐使用规范
查看>>
Webpack Critical CSS 提取与内联教程
查看>>
mysql优化概述(范式.索引.定位慢查询)
查看>>
MySQL优化的一些需要注意的地方
查看>>
mysql优化相关
查看>>
MySql优化系列-优化版造数据(存储过程+函数+修改存储引擎)-2
查看>>
MySql优化系列-进阶版造数据(load data statment)-3
查看>>
MySql优化系列-造数据(存储过程+函数)-1
查看>>
MySQL优化配置详解
查看>>
Mysql优化高级篇(全)
查看>>
mysql会员求积分_MySql-统计所有会员的最高前10次的积分和
查看>>
mysql会对联合索性排序优化_MySQL索引优化实战
查看>>
MySQL作为服务端的配置过程与实际案例
查看>>