设计模式-->Singleton(单例模式)

本文深入探讨了单例模式的应用及其与缓存模式的结合使用,通过具体代码实例展示了如何在Java中实现单例模式,并解释了其在功能菜单等场景下的优势。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

单例模式,也就是在系统中只存在一个事例。它的应用还是比较广泛的,例如产品的功能菜单(功能树),系统上线以后,它就很少进行修改了,为了提供系统的性能,可以在系统中只存在这样一个功能菜单事例。这样单例模式也往往和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函数中增加相同的代码,编译就不能通过了。

转载于:https://www.cnblogs.com/swingboat/archive/2005/03/22/123586.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值