I need to implement an application from several manufacturers / several consumers for a university course and have difficulty finding a solution to the next problem, which does not make me feel like I'm something wrong;)
I need to implement a Producer
that creates the given Component
type ( CPUComponent
, MainboardComponent
). All subclasses of the general class Component
). Each instance of Producer
will produce only a certain amount of one type of component (for example, only motherboards), and then shuts down.
Component
- all more or less immutable objects (only final
fields), and all the logic is implemented in the common base class Component
(simplified below)
public abstract class Component implements Serializable { private final long id; public Component(int id) { ... } public long getId() { return id; } }
Component
subclasses are simply primitive, like
public class CPUComponent extends Component { public CPUComponent(long id) { ... } }
With a language that is Java, I cannot easily solve this problem using Generics (since I could in C #, because I cannot create new type parameter objects in Java). So I started to implement Factory
public interface ComponentFactory { Component createComponent(Producer producer, boolean defective); }
And specify specific factory implementations for each type of Component
.
Now the problem is that when I want to save the created components in the Storage
class (just controls all the produced components for consumers), I need to find out the exact type of objects (each CPUComponent
, etc. in its own shelf), but I only get Component
(base type) from factory.
So the only thing that will help now is instanceof
, but I think there should be a better solution for my problem.
Another solution I can imagine would be to implement Producer
for each type of Component
, but I wanted to avoid it.
Perhaps Iām thinking about how complicated and already completely redid it all. Just point me in the right direction;)