I have a library project which contains an abstract class, let’s say ClassA. In the project that uses that library project, I have ClassB that extends ClassA.
Now here’s my problem. In the library project I want to use an instance of the implemented ClassB, but I have no idea how to retrieve that instance. Is there any pattern or other ideas for this?
Here’s a simple diagram of the situation.
Edit
The reason I’m asking is that I’m creating multiple applications, which only have different methods in ClassB. Therefore I’m creating a library that all of these applications can use, only having to extend ClassA. These applications are separate projects, using the library.
What you’re looking for is something like the Abstract Factory pattern. The application code (the code that calls into the library) would, at some point, need to pass in a Factory class that would be used by the library to create instances of ClassA objects. In your case, the Factory class would generate instances of ClassB.
Depending on the design and functionality of the classes, it’s likely that ClassA should be redesigned as an interface, or at least as an abstract class, as part of this refactoring.
EDIT:
Here’s an untested pseudo example:
This code would be in the library
This code would be in the application: