I am designing Traveller App. For which I need to design 'Traveller' class and with its instance I should be able to access properties of different types of Travel modes.
class Traveller {
// common properties.
}
class RoadTravel {
// properties specific to class
}
class WaterTravel {
// properties specific to class
}
class RailTravel {
// properties specific to class
}
from the above code , I just want to create instance of 'Traveller' class and should be able to access the properties of all other classes (RoadTravel,WaterTravel,RailTravel).
I dont want to create any dependency on my sub classes and also my instance variables should not be final.
Please suggest good way of implementation so that it should be easy to add any new type of Travel mode in future.
In Java you cannot have a class which extends (inherits) from multiple classes. (You might want to look into the Deadly Diamond of Death Problem.
In your case, what you could have would be a Travel interface which defines the behaviour each of your travel types need to expose, such as cost(int duration), getName(). etc/
Your logic would then use the Travel interface to do it's logic. The travel type dependent logic would be stored in the seperate classes which make use of the Travel interface. Your main logic would then delegate travel specific logic to these classes which are passed to it at run time.
You will need to take a look at the Strategy Design Pattern to see how you can implement this.
A way to implement multiple inheritance in java is the use of proxies.
Your requirements do not seem very clear and so I cannot suggest a complete solution.
If you provide an example of client code that will use these classes, I can suggest in more details how to implement it using proxies.
Related
In Java, I have an abstract class Player and the two classes Striker and Defender they both extend the abstract class Player. I have an Interface IAttack and an Interface IDefend. In those 2 interfaces there is the prototype of only one method - the method shoot(for the Interface IAttack) and the method tackle(for the interface IDefend). I've implemented the method shoot(resp. tackle) in the class Striker(resp Defender).With this hierarchy I can create Strikes, who can only shoot the ball to a given distance. I can create defenders, who can tackle somebody only with a given intensity.
What I want is to be able to create strikers(resp. defenders) who can do different tasks(and not only shoot to a given distance). For example I'd like to have a striker who can shoot a penalty, a striker who can play with its head etc.
How can I do that? Do I need necessarily to create more classes for the strikers(I mean a class for the strikers who shoot penalties, a class for the striker who play with head). Is there a more elegant way to have strikers who can do multiple tasks?
Couple of ways to implement it.
1) Let another Stricker class implement both IShootPenalty, and IAttack behavior. You can create individual required interfaces, and let each player object implement appropriate interfaces. Mix and match them as required.
(or)
2) Create boolean flags for each behavior in abstract class, and set the appropriate flags based on required behavior.
Stricker.setShootPenality(true);
Striker.setShooter(true);
A nice way would be to have all the properties in a different class.
Say for example, a class called StrikerProperties.java.
You can have different variables here and set them true or false depending upon the other characteristics of the player. This will enable you to use this for different objects, and also different classes, in cases you want to make teams and all later.
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:
The data Singleton should be a singleton, as implied by its name.
Some of the shared logic in the shared project uses the DataSingleton, so the DataSingleton must also be in the shared-classes project (otherwise I get a build error).
I don't want to put the application-specific logic in the shared project.
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?
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 DataFetchers (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.
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.
I have a set of classes from third party library which I don't have access to the source. I need to add some common behavior on these objects by using a design pattern. How do I apply Decorator or Visitor pattern to these objects?
These objects have no common base class. These are either plain objects or having uncommon interfaces. I cannot add a common interface to these classes because these classes are not part of my project.
How do I add common behavior to these classes without checking ‘instance of’ in a single method.
To work with Decorator you need some well defined interface. So the first task is to find an interface. As third party classes dont have an interface, Adapter pattern comes to rescue. You can define your own interface and adapt the third party classes to interfaces you require them to adhere to.
class YourTypeAdapter implements YourAdapterInterface{
private Type instance; //need to adapt this as no interface present
public void interfaceMethod(){
instance.someTypeSpecificMethod();
//perform extra steps here
}
}
In this way you can adapt those Types which do not have a common interface into a suitable interface hierarchy for you. You can also add additional functionality that you want to add to this adapter. Or you can go ahead and use a decorator to YourTypeAdapter as now you have an interface YourAdapterInterface to work with.
References:
- OODesign Adapter pattern
I need to use two similar libraries one for one specific session of MVC. Means, they (their methods) won't be used simultaneously (I'll use If...Else around that specific session to choose methods of only one library at a time). The problem is:
For both libraries to work, its mandatory for my Entities (Model) to extend their classes (wished I was with C++).
They don't provide any Interface. So, I can't do multi-inheritance.
The only choice I have left: Create two different Models each for both libraries & use specific Model based on session (or being used libraries).
But, it'll duplicate the codes in Models. At this time there's no need to sync data between them due to use of persistent storage between MVC sessions. But still, duplicate code is a big headache to manage. Is there a way to avoid this?
You could create Adapters for each specific libraray. This would keep your own code clean from the other libraries.
Also you should consider using the Strategy Pattern for switching between both libraries. This becomes handy when the code becomes more complex and you can mock the libraries in tests.
You can't get around including both libraries if that's what you're asking. You could have a few options just depends on how you want things to work.
From what I understand, you could create two classes, each extending a different library, these classes implement an Interface, override any methods you need to.
Pseudo code:
private class Lib1Adapter extends Lib1 implements LibAdapter {
// wrapper methods call lib1 methods
}
private class Lib2Adapter extends Lib2 implements LibAdapter {
// wrapper methods call lib2 methods
}
public interface LibAdapter {
// method signatures for publicly accessible methods
}
public class YourModel {
public LibAdapter la = < boolean statement > ? new Lib1Adapter() : new Lib2Adapter();
}
Here's something that's got me a bit stumped but intrigued all the same. In my Android game I have various Levels that extend the superclass Level. What I am trying to do is build a levelDirectory (based on the Singleton DP) that essentially is an object that has a HashMap object within it that stores all the Level subclasses. Here is my question:
We're all familiar with the enhanced for loop, but how can I write something that would be the equivalent of
for(Level l : An Array Of Every Level Subclass In My Project that is an Extension of the Level Superclass){
HashMap.put(l.name, l);
}
I am trying to build a system that can dynamically update itself when I add more and more level subclasses. I know having a method in Level that submitted itself to the static Directory and was called in the Level's constructor is an option, But I'm just wondering whether there is a way of doing what I said above in that enhanced for loop?
Many thanks
The question itself is wrong. You cannot loop over List ("Every Level Subclass In My Project") and get instances of Level. l should be Class.
From the context, I think you meant "every instance of every Level subclass". No, it is not possible - a virtual machine is not and should not be a database. You cannot just query for objects, you have to manage references in your code (but that you already knew that - your constructor solution will work).
Option 1:
Lately I had to solve a similar problem within JavaSE. I'm using the Google Reflections Library for that:
http://code.google.com/p/reflections/
However I'm not sure if it can run with Android. I think it's worth to give it a try, since it's quite easy to use. In your case you would do something like:
Reflections reflections = new Reflections("my.project.prefix");
Set<Class<? extends Level>> subTypes = reflections.getSubTypesOf(Level.class);
That would give you a Set (subTypes) to iterate on and put it in the HashMap.
Option 2:
You could maybe use custom annotations to annotate your Level classes, for example:
#Level public class MyCustomLevel {}
Then use a custom annotation processor which implements AbstractProcessor to process the annotation at compile time. Implement the process method to find all classes annotated with your #Level annotation. Now you can write the full names of the found classes to a property file in your META-INF dir. From your application you can read this property file and instantiate the classes using reflection.
If you're trying to dynamically fetch the list of all classes that extend Level at runtime, that's not really possible, I'm afraid. Have a look at this thread: How do you find all subclasses of a given class in Java?
I think you might want to make the level an interface and then check if it's an interface.
In its most common form, an interface is a group of related methods with empty bodies. A bicycle's behavior, if specified as an interface, might appear as follows:
interface Bicycle {
void changeCadence(int newValue); // wheel revolutions per minute
void changeGear(int newValue);
void speedUp(int increment);
void applyBrakes(int decrement);
}
To implement this interface, the name of your class would change (to a particular brand of bicycle, for example, such as ACMEBicycle), and you'd use the implements keyword in the class declaration:
class ACMEBicycle implements Bicycle {
// remainder of this class implemented as before
}
Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.
I think standard way in the "spirit" of java is the service provider pattern.
Add a declaration file in the META-INF/services of the "plugin" jar and use java.util.ServiceLoader (http://developer.android.com/reference/java/util/ServiceLoader.html) to enumerate your providers.
Don't know much about Android but sounds like Reflection might help here, so what do you know about reflection in Java?
EDIT
Didn't know you had to limit yourself to loaded levels. That being the case you would want to do your tracking on every instance as it is created pretty much like you proposed in your question.
My idea involved parsing all the directories of a project looking for subclasses - it could be done once at the start of program execution but it would list levels that may never get instantiated...