Singleton单例模式

本文深入探讨了单例模式的原理与应用,通过两个具体示例展示了如何在Java中实现单例模式,并分析了其在不同场景下的优缺点。

public class SingletonA
{
//私有属性
private static int id = 1;

//SingletonA的唯一实例
private static SingletonA instance = new SingletonA();

/*
* 将构造函数私有,防止外界构造SingletonA实例
*/
private SingletonA()
{

}

/**
* 获取SingletonA的实例
* @return
*/
public static SingletonA getInstance()
{
return instance;
}

/**
* 获取实例的id,synchronized关键字表示该方法是线程同步的,即任一时刻最多只能
* 有一个线程进入该方法
* @return 返回id属性
*/
public synchronized int getId()
{
return id;
}

/**
* 将实例的id加1
*/
public synchronized void nextId()
{
id++;
}
}


public class SingletonB
{
//私有属性
private static int id = 1;
//SingletonB的唯一实例
private static SingletonB instance = null;

/*
* 将构造函数私有,防止外界构造SingletonB实例
*/
private SingletonB()
{

}

/**
* 获取SingletonB的唯一实例,使用synchronized关键字保证某一时刻只有
* 一个线程调用方法
* @return
*/
public static synchronized SingletonB getInstance()
{
//如果instance为空,便创建一个新的SingletonB实例,否则,返回已有的实例
if(instance==null)
{
instance = new SingletonB();
}
return instance;
}

public synchronized int getId()
{
return id;
}

public synchronized void nextId()
{
id++;
}
}


/**
* 模式名称:单例模式
* 模式特征:只能创建该类的一个实例
* 模式用途:提供一个全局共享类实例
*/
public class SingletonTest
{
public static void main(String args[])
{
SingletonA a1 = SingletonA.getInstance();
SingletonA a2 = SingletonA.getInstance();

System.out.println("用SingletonA实现单例模式");
System.out.println("调用nextId方法前:");
System.out.println("a1.id=" + a1.getId());
System.out.println("a2.id=" + a2.getId());
a1.nextId();
System.out.println("调用nextId方法后:");
System.out.println("a1.id=" + a1.getId());
System.out.println("a2.id=" + a2.getId());

SingletonB b1 = SingletonB.getInstance();
SingletonB b2 = SingletonB.getInstance();
System.out.println("用SingletonB实现单例模式");
System.out.println("调用nextId方法前:");
System.out.println("b1.id=" + b1.getId());
System.out.println("b2.id=" + b2.getId());
b1.nextId();
System.out.println("调用nextId方法后:");
System.out.println("b1.id=" + b1.getId());
System.out.println("b2.id=" + b2.getId());
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值