import java.util.*; public class ArbreSyntaxique extends ArbreImp implements Observer { protected int valeur; private static int index; /* Crée l'arbre syntaxique correspondant à l'expression commençant à lexemes[index]. */ private ArbreSyntaxique(String [] lexemes, boolean debut) throws ErreurSyntaxiqueException { super(null); if (debut) { index = 0; } try { IOperateur op = Operateur.operateur(lexemes[index++]); int n = op.arite(); int [] operandes = new int[n]; changerData(op); if (n == 0) { ((VariableObservable) op).addObserver(this); } else { for (int j = 0; j < n; j++) { ArbreSyntaxique fils = new ArbreSyntaxique(lexemes, false); ajouterFils(fils); operandes[j] = fils.valeur; } } valeur = op.evaluer(operandes); } catch (OperateurInexistantException e) { throw new ErreurSyntaxiqueException(lexemes, index); } } public ArbreSyntaxique(String [] lexemes) throws ErreurSyntaxiqueException { this(lexemes, true); } public int valeur() { return valeur; } public void update(Observable obs, Object o) { miseAJour(); } public void miseAJour() { IOperateur op = (IOperateur) data(); int [] operandes = new int[op.arite()]; int i = 0; for (Iterator it = fils(); it.hasNext();) { operandes[i++] = ((ArbreSyntaxique) it.next()).valeur; } valeur = op.evaluer(operandes); if (pere() != null) { ((ArbreSyntaxique) pere()).miseAJour(); } } public static void main(String[] args) { try { new Operateur("+", 2) { public int evaluer(int [] operandes) { return operandes[0] + operandes[1]; } }; new Operateur("-", 2) { public int evaluer(int [] operandes) { return operandes[0] - operandes[1]; } }; IVariable a = new VariableObservable("a", 0); IVariable b = new VariableObservable("b", 2); IVariable c = new VariableObservable("c", 4); ArbreSyntaxique arbre = new ArbreSyntaxique(args); System.out.println("pour " + a + ", " + b + ", " + c + " resultat = " + arbre.valeur()); a.changerValeur(1); System.out.println("pour " + a + ", " + b + ", " + c + " resultat = " + arbre.valeur()); } catch (ErreurSyntaxiqueException e) { throw new Error(e.getMessage()); } catch (OperateurExistantException e) { throw new Error(e.getMessage()); } } }