Created
December 19, 2012 05:06
-
-
Save dtinth/4334526 to your computer and use it in GitHub Desktop.
Design Patterns Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Date; | |
import javax.swing.JFrame; | |
import javax.swing.JTextArea; | |
public class WtfWtf { | |
// concrete logger but uses different interface | |
class UiLogger { | |
private JTextArea textArea; | |
public UiLogger() { | |
JFrame frame = new JFrame(); | |
frame.setSize(400, 500); | |
frame.setVisible(true); | |
textArea = new JTextArea(); | |
frame.add(textArea); | |
} | |
public void addMessage(String text) { | |
textArea.setText(textArea.getText() + "\n" + text); | |
} | |
} | |
// the log interface to unify all the logging things! | |
interface Log { | |
public void log(String string); | |
} | |
// just an implementation of a log | |
class ConsoleLogger implements Log { | |
@Override | |
public void log(String string) { | |
System.out.println(string); | |
} | |
} | |
// adapter pattern - we adapt the different interface to log interface | |
class UiLogAdapter implements Log { | |
private UiLogger logger; | |
public UiLogAdapter(UiLogger logger) { | |
this.logger = logger; | |
} | |
@Override | |
public void log(String string) { | |
logger.addMessage(string); | |
} | |
} | |
// composite pattern - log to multiple places | |
class CompositeLogger implements Log { | |
private Log[] logs; | |
public CompositeLogger(Log[] logs) { | |
this.logs = logs; | |
} | |
@Override | |
public void log(String string) { | |
for (Log log : logs) log.log(string); | |
} | |
} | |
// decorator pattern - when logging, log current time too | |
class DateLogDecorator implements Log { | |
private Log log; | |
public DateLogDecorator(Log log) { | |
this.log = log; | |
} | |
@Override | |
public void log(String string) { | |
log.log(String.format("[%tT] %s", new Date(), string)); | |
} | |
} | |
// main code | |
public void run() { | |
Log[] logs = { new UiLogAdapter(new UiLogger()), | |
new ConsoleLogger() }; | |
Log log = new CompositeLogger(logs); | |
log = new DateLogDecorator(log); | |
log.log("start program"); | |
log.log("connect to database"); | |
try { Thread.sleep(1000); } catch (InterruptedException e) { } | |
log.log("connect finished"); | |
// armse pattern - log "armse" for all debugging purposes | |
log.log("armse"); | |
} | |
public static void main(String[] args) { | |
new WtfWtf().run(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment