Back
Close

Design Pattern Factory & Abstract Factory

NicolasAirault
1,744 views

L'exemple que nous allons voir permet de créer des Ordinateur qui seront soit des PC soit des Serveurs.

Étape 1

Création de la classe abstraite Computer (la classe mère).

public abstract class Computer {
	
	public abstract String getRAM();
	public abstract String getHDD();
	public abstract String getCPU();
	
	@Override
	public String toString(){
		return "RAM= "+this.getRAM()+", HDD="+this.getHDD()+", CPU="+this.getCPU();
	}
}

Étape 2

Création des classes PC et Server (les classe filles extraite de la classe Computer ci-dessous).

public class PC extends Computer {

	private String ram;
	private String hdd;
	private String cpu;
	
	public PC(String ram, String hdd, String cpu){
		this.ram=ram;
		this.hdd=hdd;
		this.cpu=cpu;
	}
	@Override
	public String getRAM() {
		return this.ram;
	}

	@Override
	public String getHDD() {
		return this.hdd;
	}

	@Override
	public String getCPU() {
		return this.cpu;
	}

}
public class Server extends Computer {

	private String ram;
	private String hdd;
	private String cpu;
	
	public Server(String ram, String hdd, String cpu){
		this.ram=ram;
		this.hdd=hdd;
		this.cpu=cpu;
	}
	@Override
	public String getRAM() {
		return this.ram;
	}

	@Override
	public String getHDD() {
		return this.hdd;
	}

	@Override
	public String getCPU() {
		return this.cpu;
	}

}

Étape 3

Création de la classe ComputerFactory qui contient les méthodes nécessaires à la création d'un Computer.

public class ComputerFactory {

	public static Computer getComputer(String type, String ram, String hdd, String cpu){
		if("PC".equalsIgnoreCase(type)) return new PC(ram, hdd, cpu);
		else if("Server".equalsIgnoreCase(type)) return new Server(ram, hdd, cpu);
		
		return null;
	}
}

Voici le diagramme de classe correspondant à cet exemple :

Diag_design

Étape 4

Création d'une classe Main qui utilise l'implémentation du modèle de conception ci-dessus.

abstract class Computer {...}
class PC extends Computer {...}
class Server extends Computer {...}
class ComputerFactory {...}
class Main {
public static void main(String[] args) {
Computer pc = ComputerFactory.getComputer("pc","2GB","500GB","2.4GHz");
Computer server = ComputerFactory.getComputer("server","16GB","1TB","2.9GHz");
System.out.println("Factory PC Configuration : " + pc);
System.out.println("Factory Server Configuration : " + server);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants