设计模式-->Singleton(单例模式)
2005-03-22 16:35
411 查看
单例模式,也就是在系统中只存在一个事例。它的应用还是比较广泛的,例如产品的功能菜单(功能树),系统上线以后,它就很少进行修改了,为了提供系统的性能,可以在系统中只存在这样一个功能菜单事例。这样单例模式也往往和Caching(缓存)模式同时使用。
package yhp.test.pattern.singleton;
public class TestSingleton {
private static TestSingleton _instance;
public static TestSingleton getInstance(){
if(_instance==null)
_instance=new TestSingleton();
return _instance;
}
private TestSingleton(){} //保证了不能直接new
private int _x=0;
public int get_x() {
return _x;
}
public void set_x(int _x) {
this._x = _x;
}
public static void main(String[] args) {
TestSingleton first=TestSingleton.getInstance();
TestSingleton second=TestSingleton.getInstance();
first.set_x(4);
System.out.println("First instance X's Value is:"+first.get_x()); //输入:4
System.out.println("Sesond instance X's Value is:"+second.get_x()); //输入:4
}
}
有点奇怪的是:我在main函数中增加以下代码:
try{
TestSingleton test= new TestSingleton();
test.set_x(6);
System.out.println("new instance X's Value is:"+test.get_x());
}catch(Exception e){
System.out.println("单例模式对象是不允许被new的!");
}
在eclipse中运行,竟然能够编译通过,而且输出了6,但新建一个类,在main函数中增加相同的代码,编译就不能通过了。
package yhp.test.pattern.singleton;
public class TestSingleton {
private static TestSingleton _instance;
public static TestSingleton getInstance(){
if(_instance==null)
_instance=new TestSingleton();
return _instance;
}
private TestSingleton(){} //保证了不能直接new
private int _x=0;
public int get_x() {
return _x;
}
public void set_x(int _x) {
this._x = _x;
}
public static void main(String[] args) {
TestSingleton first=TestSingleton.getInstance();
TestSingleton second=TestSingleton.getInstance();
first.set_x(4);
System.out.println("First instance X's Value is:"+first.get_x()); //输入:4
System.out.println("Sesond instance X's Value is:"+second.get_x()); //输入:4
}
}
有点奇怪的是:我在main函数中增加以下代码:
try{
TestSingleton test= new TestSingleton();
test.set_x(6);
System.out.println("new instance X's Value is:"+test.get_x());
}catch(Exception e){
System.out.println("单例模式对象是不允许被new的!");
}
在eclipse中运行,竟然能够编译通过,而且输出了6,但新建一个类,在main函数中增加相同的代码,编译就不能通过了。
相关文章推荐
- 设计模式 Singleton
- PHP设计模式----单例模式(singleton)
- Singleton设计模式活学活用: 请求单一 vs 线程单一
- 设计模式学习1 Singleton
- 设计模式之单例模式(Singleton)
- 单例(Singleton)设计模式
- 26种设计模式之Singleton(单例模式)
- 23种设计模式之单例模式(创建型,3 Singleton,c++实现)
- 设计模式之Singleton
- Java设计模式—singleton 单例
- [设计模式]Singleton - 单例模式
- 单子(Singleton)设计模式
- Java设计模式透析之 —— 单例(Singleton)
- Singleton 设计模式
- 设计模式(Design Pattern) —— 单例模式(Singleton) (一)
- 设计模式:Singleton模式
- 【设计模式学习笔记】Singleton单件模式
- 胖虎白话学习设计模式之多线程与单例模式设计模式(Singleton)
- 单子(Singleton)设计模式
- Java设计模式之 —— 单例(Singleton)