静态类和单例模式之间存在什么实际的区别?
两者都可以在没有实例化的情况下调用,两者都只提供一个“实例”,而且都不是线程安全的。还有其他区别吗?
静态类和单例模式之间存在什么实际的区别?
两者都可以在没有实例化的情况下调用,两者都只提供一个“实例”,而且都不是线程安全的。还有其他区别吗?
当前回答
静态类示例
public class Any {
private static Any instance = new Any();
private Singleton() {
System.out.println("creating");
}
}
单例模式只存在一个实例:
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {
System.out.println("creating");
if (instance != null) {
throw new RuntimeException("Imposible create a new instance ");
}
}
}
其他回答
Java中的静态类只有静态方法。这是一个集装箱功能。它是基于程序编程设计创建的。
Singleton类是面向对象设计中的一种模式。单身汉类在JVM中只有一个对象实例。这种模式是以始终只有一个实例的方式实现JVM中存在的类。
是什么让你说单例或静态方法都不是线程安全的?通常,这两者都应该实现为线程安全的。
单例和一堆静态方法之间的最大区别是,单例可以实现接口(或从有用的基类派生,尽管在我的经验中这不太常见),因此您可以将单例作为“另一个”实现来传递。
单例的另一个优点是它可以很容易地序列化,如果您需要将其状态保存到磁盘或远程发送到某个位置,这可能是必要的。
从测试角度来看,Singleton是更好的方法。与静态类不同,singleton可以实现接口,您可以使用mock实例并注入它们。
在下面的示例中,我将对此进行说明。假设您有一个使用getPrice()方法的方法isGoodPrice(。
提供getPrice功能的singleton:
public class SupportedVersionSingelton {
private static ICalculator instance = null;
private SupportedVersionSingelton(){
}
public static ICalculator getInstance(){
if(instance == null){
instance = new SupportedVersionSingelton();
}
return instance;
}
@Override
public int getPrice() {
// calculate price logic here
return 0;
}
}
getPrice的使用:
public class Advisor {
public boolean isGoodDeal(){
boolean isGoodDeal = false;
ICalculator supportedVersion = SupportedVersionSingelton.getInstance();
int price = supportedVersion.getPrice();
// logic to determine if price is a good deal.
if(price < 5){
isGoodDeal = true;
}
return isGoodDeal;
}
}
In case you would like to test the method isGoodPrice , with mocking the getPrice() method you could do it by:
Make your singleton implement an interface and inject it.
public interface ICalculator {
int getPrice();
}
最终Singleton实施:
public class SupportedVersionSingelton implements ICalculator {
private static ICalculator instance = null;
private SupportedVersionSingelton(){
}
public static ICalculator getInstance(){
if(instance == null){
instance = new SupportedVersionSingelton();
}
return instance;
}
@Override
public int getPrice() {
return 0;
}
// for testing purpose
public static void setInstance(ICalculator mockObject){
if(instance != null ){
instance = mockObject;
}
测试等级:
public class TestCalculation {
class SupportedVersionDouble implements ICalculator{
@Override
public int getPrice() {
return 1;
}
}
@Before
public void setUp() throws Exception {
ICalculator supportedVersionDouble = new SupportedVersionDouble();
SupportedVersionSingelton.setInstance(supportedVersionDouble);
}
@Test
public void test() {
Advisor advidor = new Advisor();
boolean isGoodDeal = advidor.isGoodDeal();
Assert.assertEquals(isGoodDeal, true);
}
}
如果我们选择使用静态方法来实现getPrice(),那么很难模拟getPrice)。您可以使用power mock模拟静态,但并非所有产品都可以使用它。
扩展Jon Skeet的答案
单例和一堆静态方法之间的最大区别是,单例可以实现接口(或从有用的基类派生,尽管这是不太常见的IME),因此您可以将单例作为“另一个”实现来传递。
当单元测试一个类时,单体更容易处理。无论您将单例作为参数(构造函数、setter或方法)传递到何处,您都可以替换单例的一个被嘲笑或存根的版本。