// stubs: Color and Dictionary don't work; we just want the rest to type-check class Color { public Color(String s) {} } class Dictionary { public static Dictionary findDictionary(String language) { return null; /*...*/ } public boolean contains(String s) { return true; /*...*/ } /*...*/ } /* Here we move responsibility for remembering to "do stuff" after the word changes to StyledWord, but we give up extensibility -- we have 'hard-coded' the possibility of spell-checking and Q-removal into StyledWord. Bad design due to lack of extensibilty and backward dependencies, but this is a "pedagogical stepping stone" to later versions. */ class StyledWord { private StringBuffer text = new StringBuffer(); private Color color = new Color("black"); private Spellchecker spellchecker = null; private QRemover qremover = null; public StyledWord() { } public StyledWord(Spellchecker c) { spellchecker = c; } public StyledWord(QRemover n) { qremover = n; } public StyledWord(Spellchecker c, QRemover n) { spellchecker = c; qremover = n; } private void afterWordChange() { if(spellchecker != null) { spellchecker.performSpellcheck(this); } if(qremover != null) { qremover.removeQs(this); } } public void addLetter(char c, int position) { text.insert(position,c); afterWordChange(); } public void deleteLetter(int position) { text.delete(position,position+1); afterWordChange(); } public String getText() { return new String(text); } public Color getColor() { return color; } public void setColor(Color c) { color = c; } /*...*/ } class QRemover { public QRemover() { } public void removeQs(StyledWord word) { // subtle that we can delete only one Q but we'll get // called-back again after changing the text int i = word.getText().indexOf('Q'); if(i!=-1) word.deleteLetter(i); } } class Spellchecker { private Dictionary dictionary; public Spellchecker(String language) { dictionary = Dictionary.findDictionary(language); } public void performSpellcheck(StyledWord word) { if(dictionary.contains(word.getText())) { word.setColor(new Color("black")); } else { word.setColor(new Color("red")); } } } class Main { public static void main(String[] args) { StyledWord w = new StyledWord(new Spellchecker("English")); // ... use w in various methods in the application } }