Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 2 Current »

package SingletonPatternDemo;
public class ReportHeader {
    private static volatile ReportHeader instance;
    private String header;

    // Private constructor
    private ReportHeader() {
        // Code to initialize the header
        this.header = "ABC Programming Company\nSan Antonio Office\n210-837-1234\n\n";
    }

    // Public method to get instance
    public static ReportHeader getInstance() {
        if (instance == null) {
            synchronized (ReportHeader.class) {
                if (instance == null) {
                    instance = new ReportHeader();
                }
            }
        }
        return instance;
    }

    public String getHeader() {
        return this.header;
    }

    // New printHeader method
    public void printHeader() {
        System.out.println(this.header);
    }
}
package SingletonPatternDemo;

public class SingletonDemo {
    public static void main(String[] args) {
        ReportHeader reportHeader = ReportHeader.getInstance();
        reportHeader.printHeader(); // Using the new printHeader method

        // Write report
    }
}

Let's consider a Report Header Singleton class that provides a consistent header for all reports generated by the system. The Singleton ensures that we only create one instance of the header for efficiency and consistency.

In the above example, ReportHeader is our Singleton class. It contains a private header string that holds the report header. The getInstance method provides access to the Singleton instance.

The ReportWriter class uses the Singleton to retrieve the report header. When the ReportWriter is run, it will print the report header to the console.

This example ensures there is always a single, consistent header used across all reports in the application.

  • No labels