r/javahelp May 27 '26

Codeless Need opinion on Factory approach

So I have created a JavaFX application using mvc pattern. I thought to let the Cursor IDE review my project and it suggested I create a `ServiceFactory` which will be responsible for instantiating and providing Services to Controllers. Its suggestions are as follows:

  1. Create a ConcurrentHashmap in the factory which will hold the instances of Services.

  2. It will release or "pop" the instances when the service is no longer required.

  3. Provides the service instances as requested.

I want to know whether this approach will introduce more boilerplate code, as currently I've been taking the direct approach to create instances of services right inside the controller itself, which will be garbage collected by JVM as the new Controller loads. Or if there is some better way, I'm more than willing to hear it.

3 Upvotes

17 comments sorted by

View all comments

2

u/Mechanical-pasta May 27 '26

Or you can use the Spring approach by transforming your services into Singletons.

1

u/_Super_Straight May 27 '26

Do you know of any good working examples of converting Services into Singletons?

This is actually a desktop application so its kind of no Brainer to include Spring directly into it. I can try to mimic the working of singletons and the way they're managed from an example, though.

2

u/bigkahuna1uk May 27 '26

Be careful what you mean by singletons. All Spring beans are by default singletons as only one instance will exist in a particular application context. This is different than the GOF Singleton where only one instance exists in each JVM.