Workaround for a lack of multiple inheritance - java

I am currently working on a videogame (assignment), and the problem I have is the following:
The player can move vertically and horizontally, but some other objects can only move vertically OR horizontally. I would love to have an abstract class "HorizontalMovingObject" and "VerticalMovingObject", and have an abstract class "MovingObject" which extends both these classes. I was wondering if there happens to be a workaround for this?
I currently have these abstract classes, but find myself constantly copying code from the unidimensional moving classes to the regular moving class. I have tried a couple of things, but all felt wrong somehow. I worked through interfaces for the unidimensional moving parts, but there is a default underlying behavior that should extend to all objects moving in that direction, and thus it feels wrong to write these over and over again. I tried the reverse and have for example the horizontal class extend the MovingObject class, but with all its vertical components set to 0, which somehow felt even worse.
I know this might not seem like a very important detail, but it has been driving me crazy for some reason. Mostly because I come from C++.
Any help is appreciated!

I would love to have an abstract class "HorizontalMovingObject" and
"VerticalMovingObject", and have an abstract class "MovingObject"
which extends both these classes.
The workaround for that is interface.
MovingObject should implement both HorizontalMovingObject and VerticalMovingObject
I currently have these abstract classes, but find myself constantly
copying code from the unidimensional moving classes to the regular
moving class. I have tried a couple of things, but all felt wrong
somehow.
Java 8 introduces default methods that allow to define default implementations for interfaces.
Note that if a class implements both HorizontalMovingObject and VerticalMovingObject , which both have a same default method, you should override it to make the class compile : default interfaces allow to mix inherited behaviors from distinct interfaces while no ambiguity is present about which method is inherited. When it is not the case, a compilation error occurs.
An alternative to Java 8 interfaces default method to achieve this requirement is using the decorator pattern : define each part of behavior that you want to reuse in a specific decorator class, chain the decorators designed to work together and and add these to the decorated class that need these specific behavior.
This approach favors composition over inheritance and requires more boiler plate code but is more flexible.

One workaround that can be done for multiple inheritance is using default methods of interfaces.
I personally don't think it's a good idea, this is not what default methods are there for, but technically it's a loop-hole you can expliot
A better solution for me can be to have some MovingObjectAbs class that will hold the shared direction-agnostic logic that both horizontal and vertical classes will extend, or to have some utility classes that will have shared logic.

Related

Android Java App: Extending two classes (walk around)

I have two classes, ImageMap, extending ImageView and PageView extending GLSurfaceView, I am using the ImageMap to mainly have hot spots on drawables but I also need to add a page flip/curl animation to it, in order to do that I need those two classes to act as one object, any idea how to do that?
It is totally clear to me that multiple inheritance is not allowed in java.
There is no way of really extend two classes. What you can do is:
You make a wrapper object, that holds one instance of each object. and simply do this.ImageMap.filed1 and so. This is more convenient while developing the class. This also allows you to proxy method invocations.
You define interfaces which should be implemented, and you make a new class which implements both. This is only for class that use this class to have the interface, without really caring about the implementation.
You may need both things, since the first is about "how to do it" and the second about "how it will be presented to objects that use it".
Your question is not about Android; it's about Java.
Java does not allow for multiple inheritance.
Your reasoning is inaccurate regarding the following:
in order to do that I need those two classes to act as one object
That's not the case. An 'Activity', for example, does not have to be an event handler; it's enough if your 'Activity' can have an event handler, e.g. as an inner class which can access the Activity's variables.

How can I apply oo design patterns in this situation?

Situation: Suppose we're designing the UI of Windows 9 using Java API. We need to build up 3 classes main, BuildInWindow and ApplicationWindow.
main - the window for rendering the system UI (i.e. the start botton & wallpaper page)
BuildInWindow- windows for rendering buildt-in apps (e.g. IE)
ApplicationWindow- windows for rendering apps from third party (e.g. eclipse)
all of them have to implement 3 Java API interfaces, WindowFocusListener, WindowListener and WindowStateListener and have the methods onExit() and onCrushing().
onExit() performs when the system/built-in app/ third-party app is shut down normally
onCrushing() captures any system/application crush and send system state back to server
This is the original design:
http://i.stack.imgur.com/JAJiY.png
I have some ideas of how to design it in a OO manner, but I am not sure if that's the right way. Here's my thoughts:
Create an abstract class with method onExit() and onCrushing(). Since the code of onExit()would vary from 3 classes, it should be an abstract method & onCrushing()would be same fo all classes, so it would be an concrete method
tHE MAIN WINdow should use singleton design to ensure user only create one instance of main.
Use the facade design to save the trouble of implementing 3 interfaces to three classes
My question is I don't really understand facade design, so I am not sure if it can be applied in this case. Also I am not really sure if onExit() would be different for 3 classes and onCrushing() would perform the same function.
I tried my best to explain the question clearly...if you don't understand free free to comment. Thank you very much!
I've left some questions in a comment linked to your question but here's some guidance for you:
You shouldn't create an abstract class on the basis of both BuildInwindow and ApplicationWindow both having to have methods #onExit and #onCrushing if they are not to share any implementation. Abstract classes are most useful where there is a common implementation. An interface containing these methods would be sufficient. That said, your two windows may share other functionality and, if so, it could be shared through a common superclass (abstract if it relies on subclass implementation detail). You may find the Template Method pattern useful for managing the overall window mechanism with specific tailoring for different window types. You may also find the Factory Method means of instance creation (for your window classes) will help separate the object creation and set-up from the creation mechanism.
A single shared instance would seem sensible and a singleton would serve this purpose (so long as you're able to handle termination, etc). Alternatively, your application may just launch a single Main instance - you may even just hide the constructor through package access to ensure no others are created.
The facade pattern just serves to simplify a complex interface. It mainly does this by rolling calls to collaborating instances together under a single (coarser) interface. This wouldn't normally be a done to hide which interfaces a class supports. Indeed, publishing which interfaces a class extends is important to API users. You could roll the three interfaces into a single interface for "convenience" but I think this is unnecessary. If you do settle on a common superclass then that would "extend" the three interfaces (if all subclasses were expected to support them). It may also implement some default implementation of these interfaces (again, watch access modifiers to ensure those you intend to be can be overridden while others may be final).
Edit: Guidance
You just have to identify the classes and relationships:
I suggest you just grab some paper and draw. You already have your nouns and verbs (you can otherwise go noun and verb spotting to identify classes and methods on them).
So, why not draw a simple diagram containing all the info (A, B, C, Main, etc) and draw the relationships between them. This is your start point. You may have some confusion when working out how Main links to the window classes (given there are two kinds). Just write a note on it and move on to clarify the rest of the picture.
Next, refine your diagram to start moving common features into a single place (abstraction). You know this exists with regards to your interfaces and the methods you suggest but you may need to decide which (if any) have any common functionality. Then decide if interfaces satisfies your needs (methods are common but implementations are different) or if the implementation itself is the same and so a parent superclass may be useful (this addresses abstraction [who is responsible for what], encapsulation [individual implementations at the appropriate level] and polymorphism [which classes support common methods]). Note that, even if you settle on an superclass, you'd be wise to back it with an interface (it makes introduction of sibling or replacement classes easier in time - think maintenance).
Next, work on the issues you found. Has your draft design clarified any of them? For instance, your Main needs to know about its windows but - what type are they? So, has any of your refinement made this clearer?
Do any patterns present themselves? for this you need to already have a feel for design patterns I'm afraid so buy and absorb the GoF Design Patterns book. It'll put you in good stead for spotting patterns as you go. I'd also recommend reading this specific book before taking on any others as it's technology agnostic (and some other books arebloated with tech-specific workarounds). Perhaps study the two patterns I pointed out and see if they fit your requirement.
On the whole though, your ideas seem to be going in the right direction.

How to implement a turnoff switch when using composition (java)?

I have a very simple Player class in java that uses some strategies object all inheriting from the interface PlayerStrategy.
Some implementations of PlayerStrategy are simple but a few others are so resource intensive that I need to make sure I free resources properly when the strategy stops being used. Those strategies have an additional method: turnOff() that takes care of that.
Now if Player leaves the game I'd like it to call turnOff() in all the strategies it has that need it.
The problem is that only a few strategies need turnOff() so I don't feel comfortable adding that method to the PlayerStrategy interface.
Right now when a Player stops playing it checks through reflection if the method turnOff() exists in its strategy. But it's clunky and ugly. Is there a better way?
Avoid Reflection: Reflection is a bad idea. Wherever you can (and it seems you can), avoid it.
It's Good to have turnOff() in the Interface: If you have to use interface... believe me adding turnOff() or cleanup() method is a good idea; even if most of the subclasses will have just empty curly brackets. You wouldn't need to do extra work if they get updated in future to use some resource that requires a clean up.
You can get What You Want but the Cost is Higher: If you are really rigid and sure that subclasses wouldn't extend any other class. You may make the PlayerStrategy a abstract class with turnOff() as empty method. This will solve both your issue, but will limit the subclasses ability to extend other class.
If you do not want to change your implementations of PlayerStrategy, you can use the facade pattern to handle the turnOff.

What is the optimal way to share code between Activities with different base classes?

I have the following problem:
I have an abstract Activity class, lets call it MyAbstractActivity, that contains some code I'd like to reuse (for example: a standard service binder, common menu items, common initialization code, etc. etc.). Normally I would just use it to subclass my concrete activities and be done with it.
However, I occasionally need to use another supertype, such as a ListActivity or a MapActivity.
So the question is: how do I avoid duplicating that support code within an Activity, if I have to use another base class?
I have thought up of a solution based on the decorator pattern, like this one:
.
However, I see a problem with this approach:
What to do with protected methods (like onCreate())? Should I introduce an additional "bridge" class that makes them public for the purpose of the decorator, similarly to the way presented below (starting to look a bit byzantine...)?
Any other way?
I hope I made myself relatively clear. Thanks in advance for any feedback!
PS. Using static utility classes is not a good solution in my opinion, since it introduces a possibility of hard-to-identify programming bugs.
If I understand correctly, neither Fragments nor the Decorator Pattern are clean or appropriate solutions for what you want to accomplish. They were designed to solve other problems.
I find myself moving "support" code, or "framework" code, or "all that verbose, repetitive, boilerplate crap" to static utility methods. This isn't necessarily the approach I'd take on a non-Android project, but in my Android projects, it works pretty darn well.
Also, know that you don't need to subclass ListActivity to have a ListView.

How to make a design "loose coupling"?

I'm making a simple 3D CAD software. in the class diagram, many objects need to distinguish with others by (x,y,z). I create a class so-called "Position", but the problem is it looks highly-coupling because many classese work with position.
Any ideas?
It is not a problem per se if a type is used by many other types. In your case, graphical objects obviously (usually) have a position so the coupling looks natural and reasonable from the perspective of the domain model.
Also, the Position class is probably going to be a fairly low-level class whose interface (and probably implementation too) is not going to change very often in the long run. So there is not much chance of such changes breaking client code.
First let me say after 12 years that your design is not bad. Assuming that the positioning logic of your classes shall be called from outside, all your classes need to have and offer this logic. So it is part of the interface and you must bring the functionalities in. And this means, you must depend on it and there is a coupling. The coupling is not between your objects. So it is not as bad.
But there are always alternatives. It is known that inheritance establishes a very tight coupling. Consider for example that the positioning logic is only called internally in your class. Then you don't have any benefit in inheritance. You could as well have another class (let us call it Position). And instead of deriving from this class, you integrate an object of this class. And whenever you want to do something with the position, you call the corresponding methods of this object.
This alternative looks like a nonsense change. Why should you do this? But let us have a look at the consequences. Assume you have a class Circle. Circle has such a position object as proposed above. (By the way, see the wording "has a position" instead of "is a position". The "object-and-composition" solution seems to be quite natural.) Somewhere in a file X of your code you may have created such a Circle. And now you decide you change the positioning logic. In X you don't have to worry that this has a side effect, because the interface of Circle has not changed. It is just one object inside of Circle that has changed. That is just an implementation detail. In contrast if you would have used inheritance, you cannot just change the base class without looking if this has a negative effect to X. So this "object-and-composition" solution has actually reduced the coupling between X and the positioning logic.
You can even reduce the coupling further. With the object-and-composition solution, whenever you change the positioning logic, you have to check all your classes if this has an effect. But what about using an interface for Position. Your classes don't see an object of a type Position, but an object that fullfils an interface Position. And the actual positioning logic implements this interface. This way most of your classes' code has no dependency to the implementation of the positioning logic.
That is not the end of the game. There is still a coupling, because your classes must somehow create the position objects. So at least the constructor must go into detail and for example pass x,y,z. But what if you use something like a factory for this purpose, so that your objects just get the position without even knowing how these have been created. Then you are absolutely flexible. You can use your classes in completely different situations. For example in a two dimensional coordinate system. There is no coupling between your positioning logic and your classes any more.
I hope you see that all these options exist. I suppose in your example this is a bit over-engineered. But your question was how to reduce the coupling. And there are always ways. Combinations are of course possible. For example you can have the object-and-composition and make the position object public in your base class. But then I would ask if not inheritance would have been the better option?

Categories