单子模式

Singleton模式属于创造型模式。创造型设计类型处理的是对象创建机制。基本上,为了简化这个问题,创造型模式向我们解释了以适合特定情况的方式创建对象的问题。当我们需要确保一个特定的类中只有一个对象被实例化时,就会使用单子设计模式。创建的这个单一实例负责协调整个应用的行动。
不同的对象试图调用一个实例化为单子的对象。不同的对象试图调用一个实例化为单子的对象。这个对象的单一实例负责调用下面的方法或事件。

单子模式的准则如下:

优点:

  • 单例控制对资源的并发访问。
  • 它确保在整个应用中只有一个对象在受控状态下可用。

实现:

  • 确保只有一个类的实例存在。
  • 通过声明类的所有构造函数是私有的,提供全局实例的访问,提供一个静态方法来返回实例的引用,并且实例被存储为私有静态变量。

示例代码:

// Java Program to illustrate Difference Between
// Singleton Pattern vs Static Class.

// Here illustrating Singleton Pattern

// Importing input output classes
import java.io.*;

// Class 1
// Helper class
class SingletonEagar {

    // Declaration and definition of variable occur
    // simultaneously
    // Eager initialisation
    private static SingletonEagar instance
        = new SingletonEagar();

    // Private constructor of class 1
    private SingletonEagar() {}

    public static SingletonEagar getInstance()
    {
        return instance;
    }
}

// Class 2
// Helper Class
class Singleton {

    // Lazy declaration and initialisation
    private static Singleton instance;

    // Private constructor of Class 2
    private Singleton() {}

    public static Singleton getInstance()
    {

        // Condition check
        // When instance is null
        // a new object of Singleton class is created
        if (instance == null) {
            instance = new Singleton();
        }

        return instance;
    }
}

// Class 3
// Helper class
class SingletonSynchronizedMethod {

    private static SingletonSynchronizedMethod instance;

    // Private constructor of Class 3
    private SingletonSynchronizedMethod() {}

    public static synchronized SingletonSynchronizedMethod
    getInstance()
    {

        // Condition check
        // When instance is null
        // a new object of Singleton class is created
        if (instance == null) {
            instance = new SingletonSynchronizedMethod();
        }

        return instance;
    }
}

// Class 4
// Helper class
class SingletonSynchronized {

    private static SingletonSynchronized instance;

    // Private constructor of Class 4
    private SingletonSynchronized() {}

    public static SingletonSynchronized getInstance()
    {

        // Again, condition check
        if (instance == null) {

            // synchronized block
            synchronized (SingletonSynchronized.class)
            {

                if (instance == null) {
                    instance = new SingletonSynchronized();
                }
            }
        }
        return instance;
    }
}

// Class 5
// Main class (SingletonExample)
public class YiibaiDemo {

    // Main driver method
    public static void main(String[] args)
    {

        // Creating instance in main() method of class 1
        SingletonEagar instance1
            = SingletonEagar.getInstance();

        // Display message only
        System.out.println(instance1 + " : Singleton Eager initialisation ");

        // Creating instance in main() method of class 2
        Singleton instance2 = Singleton.getInstance();

        // Display message only
        System.out.println(instance2 + " : Singleton Lazy initialisation ");

        // Creating instance in main() method of class 4
        SingletonSynchronized instance3 = SingletonSynchronized.getInstance();

        // Display message only
        System.out.println(instance3+ " : Synchronized Singleton");
    }
}

运行结果:

SingletonEagar@33b2152a : Singleton Eager initialisation 
Singleton@31a2252a : Singleton Lazy initialisation 
SingletonSynchronized@31a2251b : Synchronized Singleton

静态类

静态嵌套类是被声明为静态的嵌套类。在Java中,静态类是将类分组的一种方便方式。Java不允许创建顶层静态类;只允许创建嵌套(内部)类。这就是为什么静态类也被称为静态内部类或静态嵌套类。

静态类的准则如下:

优点:

  • 通过使其成为静态类,可以在类内定义相关的或辅助的类。
  • 它可以通过对象引用访问包围类的私有成员。
  • 静态类为嵌套类提供了一个良好的命名空间。
  • 如果包围类被更新,我们也能在同一位置更新静态类。
  • 在JVM中,Classloader只在第一次使用时加载静态类,而不是在其包围类被加载时。

实现:

  • 静态类只能是一个内部类或一个嵌套类。
  • 静态类可以像其他静态成员一样使用任何类型的访问修改器(私有、保护、公共或默认)。
  • 静态类只能访问其包围类的静态成员。
  • 静态类只能通过其包围类的对象与非静态成员交互,因为它不能直接访问其包围类的非静态成员。

示例代码:

// Java Program to illustrate Difference Between
// Singleton Pattern vs Static Class.

// Here illustrating Static Class

// Importing input output classes
import java.io.*;

// Class 1
// Helper Class
class YiibaiDemo_Outer {

    // Custom input integer value
    static int x = 20;

    public static void display() { System.out.println(x); }
    // Class 2
    // Static inner class

    // Can access all static variables of outer class
    // Can't access non-static members
    static class YiibaiDemo_Inner {

        YiibaiDemo_Inner()
        {

            // Display message
            System.out.println(
                "This is Inner Class Constructor...");

            // Print the value of x from inside class thrown
            // on console
            System.out.println("Value of "x" from inside Inner Class is : " + x);
        }
    }

    // Main driver method
    public static void main(String[] args)
    {

        // Printing value of x in the main() method
        System.out.println(YiibaiDemo_Outer.x);

        // Calling display() method from class 1
        YiibaiDemo_Outer.display();

        // static inner class object which is as follows:
        // OuterClass.InnerClass variable = new
        // OuterClass.InnerClass();
        YiibaiDemo_Outer.YiibaiDemo_Inner object = new YiibaiDemo_Outer.YiibaiDemo_Inner();
    }
}

运行结果:

20
20
This is Inner Class Constructor...
Value of "x" from inside Inner Class is : 20

现在,已经了解了这两个概念和工作原理,并看到了它们之间确凿的差异。现在,以表格的形式来说明所有的差异,如下所示:

单例模式 静态类
Singleton是一种设计模式。 静态类基本上是在Java中把类分组的一种方式。
一旦对象被创建,内存就被分配。 当任何一个类的成员被访问时,内存会立即被分配。
单例的实现可以有静态成员或实例成员。 静态类只能包含静态成员。
单例模式可以实现任何其他接口或基类的要求。 它不能实现接口或任何其他基类。
单例类可以作为方法参数使用。 静态类不能作为方法参数使用。
Singleton模式使用Heap内存。 静态类使用堆栈内存。
单例模式在垃圾收集器的范围内工作,因为它使用堆内存。 在垃圾收集器的范围之外,因为它使用堆栈内存。
单例模式支持依赖性注入(DI)的实现,因为Singleton遵循OOPS概念。 它不能实现依赖注入(DI),因为DI是界面驱动的。
Singleton是一种架构模式,而不是一种语言特性。 静态是一种语言特性,而不是一种架构模式。
对象的处置是可能的。 它不能处置静态类,因为没有创建实例。

Java中单例模式和静态类的区别

欢迎任何形式的转载,但请务必注明出处,尊重他人劳动成果。
转载请注明:文章转载自 有区别网 [http://www.vsdiffer.com]
本文标题:Java中单例模式和静态类的区别
本文链接:https://www.vsdiffer.com/vs/difference-between-singleton-pattern-and-static-class-in-java.html
免责声明:以上内容仅代表 个人看法、理解、学习笔记、总结和研究收藏。不保证其正确性,因使用而带来的风险与本站无关!如本网站内容冒犯了您的权益,请联系站长,邮箱: ,我们核实并会尽快处理。