Reputation: 1812
I am developing two Android applications with similar -- but not identical -- logic, and I want to share code between them. Currently, I have a project for each application, and an additional project for shared classes. The shared-classes project is a library, and the application projects are linked to this library.
The problem I have is with a class that's responsible for getting data from the server and caching that data. The class is called DataSingleton. Fetching the data has some logic which is the same for both applications, and some which is different. My question is how to design the class to support this.
There are some limitations here:
If this was C++, I would have 2 different classes name DataSingleton -- one in each application -- and then have the linker connect the correct class. Both classes could inherit from some common base class, to handle the code sharing for shared logic. Can I do something similar in Java?
If it helps, I can "initialize" the DataSingleton at the start of the application with some argument that will determine its behavior. I thought about passing a class to it, but then that class doesn't have access to the DataSingleton's private members.
What is the "right" way to do this?
Upvotes: 0
Views: 233
Reputation: 115338
Think about singleton. It is a class that does 3 thigs: 1. it has a business logic 2. it creates instance of itself 4. it holds this single instance and provides access to it.
You want to hold more than one implementations of your class. This means that you need interface and/or abstract base class and several concrete classes. But in this case the best solution is to separate #1 from #2 and #3: create hierarchy of DataFetcher
s (I am sorry, I changed your name DataSingleton
because it does not describe the reality any more) and DataFetcherAccessor
:
interface DataFetcher {}
class DataFetcher1 implements DataFetcher{}
class DataFetcher2 implements DataFetcher{}
class DataFetcherAccessor<A extends DataFetcher> {
private static A accessor;
public static void setImpl(Class<A> c) {
accessor = c.newInstance();
}
public static A getAccessor() [
return accessor;
}
}
There are obviously a lot of other solutions. For example you can use SPI to locate available implementation of your interface. You can also scan your classpath yourself and discover available implementation of interface DataFetcher
or use Reflections for this.
Upvotes: 1
Reputation: 3186
Strip the DataSingleton
in the shared project of the parts that will need to change in the different projects, define it as an abstract class and change its name to AbstractDataSingleton
or something like that, then just create 2 separate classes in each product called DataSingleton
or whatever and make them extend the AbstractDataSingleton
in the shared project.
Upvotes: 0