您的位置:首页 > 其它

设计模式-->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函数中增加相同的代码,编译就不能通过了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: