










































Studia grazie alle numerose risorse presenti su Docsity
Guadagna punti aiutando altri studenti oppure acquistali con un piano Premium
Questa pagina non è visibile nell’anteprima
Non perderti parti importanti!











































Classificazione dei pattern (Gamma, Helm, Johnson and Vlissides)
public interface Trace { // turn on and off debugging public void setDebug(boolean debug); // write out a debug message public void debug(String message); // write out an error message public void error(String message); }
public class FileTrace implements Trace { private java.io.PrintWriter pw; private boolean debug; FileTrace() throws^ java.io.IOException^ { // a real FileTrace would need to obtain the filename // somewhere for the example I'll hardcode it pw = new^ java.io.PrintWriter(new java.io.FileWriter("trace.log")); } public void setDebug(boolean debug) { this.debug = debug; } public void debug( String message ) { if( debug ) { // only print if debug is true pw.println("DEBUG: " + message); pw.flush(); } } public void error(String message) { // always print out errors pw.println("ERROR: " + message); pw.flush(); } }
public static void main(String[] args) { Trace t = new SystemTrace(); ... } public class FactoryTrace { public static Trace getTrace() { try { return new FileTrace(); } catch ( java.io.IOException ex ) { Trace t = new SystemTrace(); t.error("could not instantiate FileTrace: " + ex.getMessage()); return t; } } } public static void main(String[] args) { Trace t = FactoryTrace.getTrace(); ... }
public class Singleton { private static Singleton instance; // istanza singola private Singleton() { } // costruttore public static Singleton instance() { // crea l’oggetto solo se non esiste if (instance == null) instance = new Singleton(); return instance; } // altri metodi }