I have a multi-platform system, and in order to design it I need to know how I could execute a class depending on the operating system.
I have created the following simple function Public Boolean esandroid(){....}
where if the system is android it is true otherwise it is false, In this way I have managed well placing if everywhere, but it is not practical, I want to know if there is any way to make classes depending on the operating system for example .
Class reproducir (){
...Codigo para reproducir en android...
}
Class reproducir (){
...Codigo para reproducir que no sea en android...
}
The idea is that depending on the operating system that executes the corresponding class.
Having two classes in the previous example, the same class is referenced, and it executes the one corresponding to the operating system where it currently operates. It's possible?
It uses the factory design pattern. This pattern allows you to create instances of the same interface with a specific implementation but hiding the implementation and creating the objects based on certain parameters (if necessary).
For example, define an interface called
Reproductor.java
:So now based on the types of operating systems you would initially support, you create a class that implements the interface.
For Linux:
Windows:
Android:
Now you create another class that will be in charge of creating a specific instance according to the operating system:
So the use is the simplest. You just call the method
ReproductorFactory.crearReproductor()
whenever you need the player:Note the non-existence of
if
. And if one day you were to support another OS, you would just have to add the implement of it and add it to the methodcrearReproductor()
and that's it, you won't have to make any more modifications to your entire program besides that.Object-oriented programming provides you with a very useful tool in these cases called "polymorphism" .
For your case, you have a class called
reproducir
that will have certain common methods likeempezar
,parar
,pausa
,getNumCancion
,getPosicion
, etc:Now all you have to do is create the platform-dependent implementations.
Android example:
JavaSE example:
You only have to manage which instance to actually create:
reproducir
That returned instance will be able to doempezar
,parar
andpausa
depending on each platform without having to repeat conditionsif
within your code over and over again, and furthermore, you won't have to repeat in each implementation common code likegetNumCancion
orgetPosicion
or common parts of the playback state inempezar
,parar
andpausa
.