Design Pattern Observer

Azalius
1,044 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Diagramme UML

Image

Code Java

Eleve

import java.util.List;
import java.util.ArrayList;

public class Eleve {
	
	private List<Observer> observers;
	private List<Float> notes;
	private float moyenne;
	
	public Eleve() {
		observers = new ArrayList<Observer>();
		notes = new ArrayList<Float>();
	}
	
	public void ajouterNote(float note) {
		notes.add(note);
		notifyAllObservers();
	}
	
	public void setMoyenne(float moyenne) {
		this.moyenne = moyenne;
	}
	
	public float getMoyenne() {
		return moyenne;
	}
	
	public List<Float> getNotes() {
		return notes;
	}
	
	public void attach(Observer observer){
		observers.add(observer);
	}
	
	private void notifyAllObservers() {
		for (Observer observer : observers) {
			observer.update();
		}
	}
}

Observer

public abstract class Observer {
   protected Eleve eleve;
   public abstract void update();
}

notesObserver

public class notesObserver extends Observer{

	public notesObserver(Eleve eleve){
		this.eleve = eleve;
		this.eleve.attach(this);
	}

	@Override
	public void update() {
		
		float moyenne = 0;
		
		for(float note : eleve.getNotes()) {
			moyenne += note;
		}
		
		moyenne /= eleve.getNotes().size();
		
		eleve.setMoyenne(moyenne);
	}

}

Test

1
2
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// {...}
public class Main {
public static void main(String[] args) {
Eleve eleve = new Eleve();
new notesObserver(eleve);
eleve.ajouterNote(15.0f);
System.out.println(eleve.getMoyenne());
eleve.ajouterNote(5.0f);
System.out.println(eleve.getMoyenne());
eleve.ajouterNote(13.0f);
System.out.println(eleve.getMoyenne());
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content