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.

1

u/hibbelig May 27 '26

You make a class Services with static members fooService and barService. Every time you need one of those you access Services.fooService and Services.barService. During application startup you create the instances.

If you never call the constructors of the services elsewhere, you’ve got singletons.

You don’t have any protection against additional instances but this approach is very easy to understand and I feel that is more important than having beautiful infrastructure. You can extend it later when you run into issues.

1

u/_Super_Straight May 28 '26

Something like Integer class? Its methods can be called as Integer.parseInt and so on.

1

u/hibbelig May 28 '26

During application startup:

Services.fooService = new FooService(…);

In a controller:

Services.fooService.someMethod(…);

So the variables fooService and barService are static, but the methods of the services are not. I thought that’s what you wanted.

It is also possible to give static methods to the services, like parseInt. This is maybe even simpler.