1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| public class MyCode {
private NetworkClientFactory factory;
public MyCode(NetworkClientFactory factory) {
this.factory = factory; // injection d'une factory, on ne sait pas à l'avance de quel type concret
}
public void doStuff() {
NetworkClient client = factory.createClient(); // ouvre une connexion réseau, fait plein de trucs gourmands donc j'ai besoin de maîtriser à quel moment je l'appelle
client.send("ping");
System.out.println(client.receive());
client.close();
}
}
public abstract class NetworkClientFactory { // Ma fabrique abstraite
abstract NetworkClient createClient();
}
public class TcpClientFactory extends NetworkClientFactory {
public NetworkClient createClient() {
return new TcpClient(...);
}
}
public class UdpClientFactory extends NetworkClientFactory {
public NetworkClient createClient() {
return new UdpClient(...);
}
}
public abstract class NetworkClient {
abstract void send(String message);
abstract String receive();
abstract String close();
}
public class UdpClient {
// ...
}
public class TcpClient {
// ...
} |
Partager