静态类和单例模式之间存在什么实际的区别?
两者都可以在没有实例化的情况下调用,两者都只提供一个“实例”,而且都不是线程安全的。还有其他区别吗?
静态类和单例模式之间存在什么实际的区别?
两者都可以在没有实例化的情况下调用,两者都只提供一个“实例”,而且都不是线程安全的。还有其他区别吗?
当前回答
我不是一个伟大的OO理论家,但据我所知,我认为与Singleton相比,静态类唯一缺少的OO特性是多态性。但如果您不需要它,那么使用静态类,您当然可以继承(不确定接口实现)以及数据和函数封装。
Morendil的评论,“静态类中体现的设计风格纯粹是程序性的”我可能是错的,但我不同意。在静态方法中,您可以访问静态成员,这与单例方法访问其单个实例成员完全相同。
编辑:我现在实际上在想,另一个区别是,静态类在程序开始时被实例化,并且在整个程序的生命周期中都存在,而单例在某个时刻被显式实例化,也可以被销毁。
*或者它可能在第一次使用时被实例化,这取决于语言,我认为。
其他回答
我们可以创建单例类的对象并将其传递给方法。Singleton类对继承没有任何限制。我们不能处理静态类的对象,但可以处理单例类。
静态类不适用于任何需要状态的对象。它对于将一堆函数放在一起非常有用,例如Math(或项目中的Utils)。所以类名只是给了我们一个线索,我们可以在哪里找到函数,而不是更多。
Singleton是我最喜欢的模式,我用它在一个点上管理一些东西。它比静态类更灵活,可以保持其状态。它可以实现接口,从其他类继承并允许继承。
我在静态和单例之间选择的规则:
如果有一堆函数应该保持在一起,那么静态就是选择。任何其他需要对某些资源进行单一访问的内容都可以作为单例实现。
一个显著的区别是Singleton附带的不同实例化。
对于静态类,它由CLR创建,我们无法控制它。使用singleton,对象在尝试访问的第一个实例上实例化。
从测试角度来看,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模拟静态,但并非所有产品都可以使用它。
a.序列化-静态成员属于类,因此无法序列化。
虽然我们已经将构造函数私有化,但静态成员变量仍将被携带到子类中。
c.我们不能进行延迟初始化,因为只有在类加载时才会加载所有内容。