12 - Exemple complet

Exemple de la bibliothèque

L’exemple est composé d’une classe Livre, d’une classe Biblio qui contient des Livres et d’une classe principale qui instancie la bibliothèque et les livres.

Classe Livre

public class Livre {
	private String titre, auteur;
	private Boolean disponible = false;
	
	public Livre(String t, String a, Boolean d) {
		this.titre = t;
		this.auteur = a;
		this.disponible = d;
	}
	
	public String toString() {
		String dispo = (this.disponible)?"disponible":"non disponible";
		return "Titre : " + this.titre + "\n Auteur : " + this.auteur
				+ "\n est " + dispo;
	}
	
	public String getTitre() {
		return this.titre;
	}
	
	public Boolean getDispo() {
		return this.disponible;
	}
	
	public Boolean setDispo(Boolean b) {
		if(this.disponible == b)
			return false;
		else {
			this.disponible = b;
			return true;
		}	
	}
}

Class Biblio

import java.util.*;

public class Biblio {
	private List<Livre> livres;
	
	public Biblio(List<Livre> l) {
		this.livres = l;
	}
	
	public void afficherLivres() {
		for(int i = 0; i < this.livres.size(); i++) {
			System.out.println(livres.get(i));
		}
	}
	
	public Boolean emprunterLivre(String t) {
		for (int i = 0; i < this.livres.size(); i++) {
			if(this.livres.get(i).getTitre() == t) {
				if(this.livres.get(i).getDispo()) {
					return this.livres.get(i).setDispo(false);
				}
			}
		}
		return false;
	}
	
	public Boolean retournerLivre(String t) {
		for (int i = 0; i < this.livres.size(); i++) {
			if(this.livres.get(i).getTitre() == t) {
				if(!this.livres.get(i).getDispo()) {
					return this.livres.get(i).setDispo(true);
				}
			}
		}
		return false;
	}
}

Classe principale

import java.util.*;

public class UseBiblio {
	public static void main(String[] args) {
		Livre l1 = new Livre("Harry Potter à l'école des sorciers", "J.K. Rowling", true);
		Livre l2 = new Livre("Le Seigneur des anneaux", "J.R.R. Tolkien", false);
		Livre l3 = new Livre("1984", "George Orwell", true);
		Livre l4 = new Livre("Orgueil et préjugés", "Jane Austen", false);
		Livre l5 = new Livre("L'Alchimiste", "Paulo Coelho", false);
		Livre l6 = new Livre("Le Petit Prince", "Antoine de Saint-Exupéry", true);
		
		List<Livre> listeLivre = new ArrayList<Livre>();
		listeLivre.add(l1);
		listeLivre.add(l2);
		listeLivre.add(l3);
		listeLivre.add(l4);
		listeLivre.add(l5);
		listeLivre.add(l6);
		
		Biblio bib = new Biblio(listeLivre);
		
		bib.afficherLivres();
		System.out.println("#########################################");
		bib.emprunterLivre("1984");
		bib.afficherLivres();
		System.out.println("#########################################");
		bib.retournerLivre("1984");
		bib.afficherLivres();
	}
}