博客
关于我
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递归查询树状表的子节点、父节点具体实现
查看>>
mysql 里对root及普通用户赋权及更改密码的一些命令
查看>>
Mysql 重置自增列的开始序号
查看>>
MySQL 高可用性之keepalived+mysql双主
查看>>
mysql-connector-java各种版本下载地址
查看>>
mysql-group_concat
查看>>
MySQL-【4】基本操作
查看>>
Mysql-丢失更新
查看>>
Mysql-事务阻塞
查看>>
Mysql-存储引擎
查看>>
mysql-开启慢查询&所有操作记录日志
查看>>
MySQL-数据目录
查看>>
MySQL-数据页的结构
查看>>
MySQL-架构篇
查看>>
MySQL-索引的分类(聚簇索引、二级索引、联合索引)
查看>>
Mysql-触发器及创建触发器失败原因
查看>>
MySQL-连接
查看>>
mysql-递归查询(二)
查看>>
MySQL5.1安装
查看>>
mysql5.5和5.6版本间的坑
查看>>