---
title: "【设计模式】单实例模式"
author: "JuliaAilse"
date: "2012-03-04T23:24:10Z"
tags: []
categories: ["非技术"]
slug: "untitled"
draft: false
lastmod: "2012-03-04T23:24:10Z"
id: 1439866
url: "https://juliaailse.iteye.com/blog/1439866"
---

单例模式（Singleton）  
**定义：**

单例模式确保某一个类只有一个 实例，而且自行实例化 并向整个系统 提供这个实例。这个类称为单例类。  
**要点：**

1、只有一个实例；

2、自行实例化；

3、向整个系统提供该实例。  
**应用场景：**

很多操作的对象是同一对象，且同时只容许一个操作操作该对象的场景。

如： 同桌两人共用一瓶颜料来画自己的作品，但颜料瓶的瓶口大小同时只能容许一个画笔蘸取颜料。就是一个生活中的典型的单例模式的应用。  
**作用：** 1、减少不必要的实例化对象，减少内存占用。2、避免程序的逻辑错误。  
**两种形式：**

（注：来自百度百科的指导。 ）  
　　第一种形式: 也是常用的形式。  
　　public class Singleton {  
　　private static Singleton instance = null;  
　　private Singleton(){  
　　//do something  
　　}  
　　public static Singleton getInstance(){  
　　if(instance==null){  
　　instance = new Singleton();  
　　}  
　　return instance;  
　　}  
　　} //这个方法不用每次都进行生成对象，第一次生成，提高了效率。而下面的方法则只要调用，就会事例化一次。  
　　第二种形式:  
　　public class Singleton {  
　　//在自己内部定义自己的一个实例，只供内部调用  
　　private static Singleton instance = new Singleton();  
　　private Singleton(){  
　　//do something  
　　}  
　　//这里提供了一个供外部访问本class的静态方法，可以直接访问  
　　public static Singleton getInstance(){  
　　return instance;  
　　}  
　　}  
**我的事例如下：**

用的是百度百科中提供的第一个方法形式，结合上面提到的生活中的事例：

单例类：

```
public class InkBottle {
	// 创建瓶口对象
	private static InkBottle bottleInterface = null;
	private String inkcolor="blue";
	// 颜料瓶的构造函数
	private InkBottle() {
		// do something	
	}

	// 得到颜料瓶口对象的方法，定义为静态，以便多个类共享。
	public static InkBottle getBottleInterface() {
		// 判断瓶口对象是否为空，为空时，创建瓶口对象（判断瓶口是否有笔，没有就蘸颜料）
		if (bottleInterface == null) {
			bottleInterface = new InkBottle();
			System.out.println("对象获得了！");
		}
		return bottleInterface;
	}
	public String getColor(){
		return inkcolor;
	}
	public String setColor(String h){
		System.out.println("颜色设置了！");
		return this.inkcolor=h;
	}
}
```

 学生A：

```
public class StudentA extends Thread {
	InkBottle auser = InkBottle.getBottleInterface();

	public void draw() {
		System.out.println(auser.getClass().getName() + "A得到颜料："
				+ auser.getColor() + " " + System.currentTimeMillis());

	}

	public void setcolor() {
		auser.setColor("red");

		System.out.println(auser.getClass().getName() + "A设置颜料：red  "
				+ System.currentTimeMillis());

	}

	public void run() {
		while (true) {
			this.draw();
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			this.setcolor();
		}
	}
}
```

 

学生B：与学生A的类似。

主方法：

```
public class Test {
	public static void main(String[] args){
		Test t=new Test();
		StudentA a=new StudentA();
		StudentB b=new StudentB();
		a.start();
		b.start();
	}
}
```