---
title: "设计模式实例"
author: "MoocherMan"
date: "2012-11-13T15:24:21Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2012-11-13T15:27:05Z"
id: 1724663
url: "https://moocherman.iteye.com/blog/1724663"
---

**1.单例模式**
  作用是保证在Java应用程序中，一个类Class只有一个实例存在。
两种方式：
方式一：

```java

package other;

public class SingletonExample {
	
	private static SingletonExample se = null;	
	private SingletonExample() {//构造方法搞成私有的，这样就可以保证其他类不能new SingletonExample了。
		// TODO Auto-generated constructor stub
	}
	public static SingletonExample getSingletonExample(){
		if(se == null)
			se = new SingletonExample();
		return se;
	}

}

```


方式2：

```java

package other;

public class SingletonExample {
	
	private static SingletonExample se = new SingletonExample();
	
	private SingletonExample() {
		// TODO Auto-generated constructor stub
	}
	public static SingletonExample getSingletonExample(){
		return se;
	}

}


```


测试：

```java

public static void main(String[] args) {
		SingletonExample se1 = SingletonExample.getSingletonExample();
		SingletonExample se2 = SingletonExample.getSingletonExample();
		
		System.out.println(se1);
		System.out.println(se2);
		
	}

```



<span style="color:red">
===========================个人学习笔记 持续积累中============================================
</span>