Use the factory design pattern. This pattern allows you to create instances of the same interface with one implemented in concrete but hiding the implementation and creating the objects based on certain parameters (if necessary).
For example, define an interface called Reproductor.java
:
public interface Reproductor
{
void reproducir(string archivo);
void pausar();
void cerrar();
}
So now based on the types of operating systems that you would initially support, you create a class that implements the interface.
For Linux:
public ReproductorLinux implements Reproductor
{
public void reproducir(string archivo)
{
// codigo para reproducir en el OS linux
}
public void pausar()
{
// codigo para pausar en el OS linux
}
public void cerrar()
// codigo para cerrar en el OS linux
}
}
Windows:
public ReproductorWindows implements Reproductor
{
public void reproducir(string archivo)
{
// codigo para reproducir en el OS Windows
}
public void pausar()
{
// codigo para pausar en el OS Windows
}
public void cerrar()
// codigo para cerrar en el OS Windows
}
}
Android:
public ReproductorAndroid implements Reproductor
{
public void reproducir(string archivo)
{
// codigo para reproducir en el OS Android
}
public void pausar()
{
// codigo para pausar en el OS Android
}
public void cerrar()
// codigo para cerrar en el OS Android
}
}
Now create another class that would be responsible for creating a specific instance according to the operating system:
public class ReproductorFactory
{
public static Reproductor crearReproductor()
{
if(esWindow)
{
return new ReproductorWindows();
}
else if(esAndroid)
{
return new ReproductorAndroid();
}
else if(esLinux)
{
return new ReproductorLinux();
}
else{
throw new Exception("Este sistema operativo no es soportado");
}
}
}
Then the use is the simplest. Just call the ReproductorFactory.crearReproductor()
method whenever you need the player:
Reproductor reproductor = ReproductorFactory.crearReproducto();
reproductor.reproducir("c:/sonido.mp3");
Note the non-existence of if
. And if one day you end up supporting another OS, you just have to add the implementation of it and add it to the crearReproductor()
method and voila, you will not have to make any more modifications to your entire program besides that.