Singleton Service with DI
This program combines Singleton pattern with dependency injection.
Problem Statement
Write a Java program to inject Singleton Service into Client.
Source Code
| 1 | class Service { |
| 2 | private static Service instance=new Service(); |
| 3 | private Service(){ } |
| 4 | public static Service getInstance(){ return instance; } |
| 5 | void serve(){ System.out.println("Singleton Service executed"); } |
| 6 | } |
| 7 | class Client { |
| 8 | private Service service; |
| 9 | Client(Service s){ service=s; } |
| 10 | void doWork(){ service.serve(); } |
| 11 | } |
| 12 | public class SingletonDI { |
| 13 | public static void main(String[] args) { |
| 14 | System.out.println("Eduinq Singleton with DI"); |
| 15 | Service s=Service.getInstance(); |
| 16 | Client c=new Client(s); |
| 17 | c.doWork(); |
| 18 | } |
| 19 | } |
Program Output
Eduinq Singleton with DI Singleton Service executed
Explanation
Service implemented as Singleton ensures single instance. - Client receives Service via constructor injection. - This combines Singletons global access with DIs decoupling. - Useful for shared services like logging or configuration. Conclusion: Shows how to combine Singleton with dependency injection.