博客
关于我
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 1264_关于mysql 出现 1264 Out of range value for column 错误的解决办法
查看>>
mysql 1593_Linux高可用(HA)之MySQL主从复制中出现1593错误码的低级错误
查看>>
mysql 5.6 修改端口_mysql5.6.24怎么修改端口号
查看>>
MySQL 8.0 恢复孤立文件每表ibd文件
查看>>
MySQL 8.0开始Group by不再排序
查看>>
mysql ansi nulls_SET ANSI_NULLS ON SET QUOTED_IDENTIFIER ON 什么意思
查看>>
multi swiper bug solution
查看>>
MySQL Binlog 日志监听与 Spring 集成实战
查看>>
MySQL binlog三种模式
查看>>
multi-angle cosine and sines
查看>>
Mysql Can't connect to MySQL server
查看>>
mysql case when 乱码_Mysql CASE WHEN 用法
查看>>
Multicast1
查看>>
MySQL Cluster 7.0.36 发布
查看>>
Multimodal Unsupervised Image-to-Image Translation多通道无监督图像翻译
查看>>
MySQL Cluster与MGR集群实战
查看>>
multipart/form-data与application/octet-stream的区别、application/x-www-form-urlencoded
查看>>
mysql cmake 报错,MySQL云服务器应用及cmake报错解决办法
查看>>
Multiple websites on single instance of IIS
查看>>
mysql CONCAT()函数拼接有NULL
查看>>