Making Classes Variable
Can any one tell me if there i开发者_高级运维s a way, and if so how to, make an activity implement an entire class based on an if then
or switch
statement, essentially making the class itself a variable? [I want to display a particular list class (activity) in a tab depending on a value received from an OnItemClicked event in another tab].
To give you an idea of what I think I might be looking for:
if(position == 1){//run class 1}
if(position == 2){//run class 2}
THANKS.
Are you looking for polymorphism?
interface MyService {
void doWork();
}
class CoolMyService {
void doWork() { /* do something */ }
}
class AnotherMyService {
void doWork() { /* do something else */ }
}
MyService service;
if(position == 1){ service = new CoolMyService(); }
if(position == 2){ service = new AnotherMyService() }
service.doWork();
I don't know how many items there are in your list, but you can adapt the example above to load objects dynamically as appropriate. Just remember that you can use polymorphism and a defined interface to ensure integrity. Then put the real work in concrete implementations.
You might want a (n abstract) factory pattern.
Take a look at it inside the Java Design Patterns
You can use broadcast receiver
if (position == 1){
sent broadcast event to one class
}if(position === 2){
sent broadcast event to another class
}
You could also look into using Class.forName()
Class oClass = Class.forName(strClassName);
Tab myTab = (Tab) oClass.newInstance();
I'm not sure I understand your problem.
My first solution would be implementing the factory pattern with dependency injection, passing the class as an argument to the factory method:
code:
Class impClass;
if (position == 1) {
impClass = First.class;
} else if (position == 1) {
impClass = Second.class;
}
Object myObject = ObjectFactory.createObject(impClass);
Abstract factory or prototype patterns fit your needs http://en.wikipedia.org/wiki/Prototype_pattern
精彩评论