Factory + Singleton Integration

This program integrates Factory and Singleton patterns.

Problem Statement

Write a Java program where Factory creates Singleton service.

Source Code

1 class Service {
2 private static Service instance=new Service();
3 private Service(){ }
4 public static Service getInstance(){ return instance; }
5 void execute(){ System.out.println("Singleton Service executed"); }
6 }
7 class ServiceFactory {
8 public Service getService(){ return Service.getInstance(); }
9 }
10 public class FactorySingleton {
11 public static void main(String[] args) {
12 System.out.println("Eduinq Factory + Singleton");
13 ServiceFactory sf=new ServiceFactory();
14 Service s1=sf.getService();
15 Service s2=sf.getService();
16 s1.execute();
17 System.out.println(s1==s2);
18 }
19 }

Program Output

Eduinq Factory + Singleton
Singleton Service executed
true

Explanation

Singleton ensures only one instance of Service. - Factory centralizes creation logic, returning Singleton instance. - This integration combines global access with controlled instantiation, useful in large systems where services must be shared consistently. Conclusion: Shows integration of Factory and Singleton patterns.

Quick Links to Explore