markdown
### 单例设计模式释义
```text
采取一定的设计方法保证整个软件系统中,对某个类只能存在一个
对象实例,并且该类只提供一个取得其对象实例的方法
```
### 单例设计
```text
首先必须将类的构造器的访问权限设置为private,这样就不能用new操作符在类的外部产生类的对象了
只能调用该类的静态方法以返回类内部对象
由于静态方法只能调用静态成员变量,所以,指向类内部产生的该类对象的变量也必须定义成静态的
```
### 代码示例
*
*二者区分在于实例创造时间*
* #### (一)懒汉式 ```text 好处: 延迟对象的创建 坏处: 线程不安全,需要搭配多线程内容 ``` ```text public class Singleton { public static void main(String[] args) { Order order = Order.getInstance(); order.showInformation(); } } class Order{ private Order(){ } private static Order instance = null; public static Order getInstance() { if (instance == null) { instance = new Order(); } return instance; } public void showInformation(){ System.out.println("单例设计模式"); } } ``` #### (二)饿汉式 ```text 坏处: 对象加载时间过长(创建时间过早) 好处: 线程安全 ``` ```text public class Singleton { public static void main(String[] args) { Bank bank = Bank.getInstance(); bank.showInformation(); } } class Bank{ private Bank(){ } private static Bank instance = new Bank(); public static Bank getInstance() { return instance; } public void showInformation(){ System.out.println("单例设计模式"); } } ``` **[返回教程主页](https://www.monody.net/p/blog-page_3.html)*
*
评论