---
title: "java的单态实现"
author: "linshenqi"
date: "2010-03-23T14:31:40Z"
tags: []
categories: ["企业架构"]
slug: "java"
draft: false
lastmod: "2010-03-23T14:31:40Z"
id: 622225
url: "https://linshenqi.iteye.com/blog/622225"
---

```java

public class Singleton {
	
//唯一接口实例
	private static Singleton instanse;	
	
//单态，接口调用方式：Singleton xxx = Singleton.getInstance();
	public static Singleton getInstance(){
		
		if(instanse == null){
			try{
				instanse = new Singleton();
			}catch(java.lang.OutOfMemoryError err){
				System.out.println("创建对象时内存溢出" + "::" + err.getMessage());
			}
		}
		
		return instanse;
	}
	
	private Singleton(){
		this.value = 0;
	}
	
	private int value;
	
	public void ondo(int value){
		this.value = value;
		System.out.println(value);
	}
}


```


调用：

```java

public static void main(String[] args) {
		Singleton ex = Singleton.getInstance();
		Singleton ex1 = Singleton.getInstance();
		ex.ondo(2);
		ex1.ondo(3);
		System.out.println(ex == ex1);

	}

```


结果：
2
3
true