I'm writing a small game of life implementation with Spring, but trying to avoid referencing the Spring context within my code. I have two interfaces, Board and Cell. In each implementation of Board it will create a 2d array of Cells at some point. The problem is that since I'm trying not to reference Spring in my code, I can't use the Spring context to get an instance of the Cell.
I was thinking that it would be a good idea to create a CellFactory to create Cells, and then in the implementation give it the Cell class that I want to use.
So my question is, is this a bad design? If so what would be a better way of achieving this?
-
You may try @autowired annotationjatanp– jatanp2016年03月13日 14:18:45 +00:00Commented Mar 13, 2016 at 14:18
-
Why are you using Spring if you are trying not to reference Spring? You are fighting against the framework and surprised that you are having difficulty?user40980– user409802016年03月14日 18:44:19 +00:00Commented Mar 14, 2016 at 18:44
-
You can use javaee dépendency injection. It's less powerfull that Spring oness but if it's enough for you Spring is compatible with them. But having classes that depends on Spring is not a problem if you're writing an application (not a library). There is pretty much 99.9999999% chance that you won't move away from Spring.Walfrat– Walfrat2016年03月15日 08:42:49 +00:00Commented Mar 15, 2016 at 8:42
-
Just use new or a factory method, You can mix and match.kiwiron– kiwiron2016年04月13日 19:29:07 +00:00Commented Apr 13, 2016 at 19:29
1 Answer 1
Infact Spring implementation is much simpler and modular. Since u already have interfaces why not instantiate them via spring? Instance would be singleton by default. You can inject cell interface in constructor at runtime using Spring (DI). Here is reference to Spring DI
http://www.mkyong.com/spring/spring-dependency-injection-di/
However if still you don't wish to use Spring then, you could implement cell with singleton pattern and get the instance when required (make sure to keep it thread safe)
-
Adding Singletons doesn't make a design better.DeadMG– DeadMG2016年05月13日 19:57:29 +00:00Commented May 13, 2016 at 19:57