public class RunFactoryMethodPattern { public static void main(String [] arguments){ System.out.println("Example for the FactoryMethod pattern"); System.out.println(); System.out.println("Creating a Contact object"); System.out.println(); Contact someone = new Contact(); System.out.println("Creating a GUI editor for the Contact"); System.out.println(); System.out.println("The GUI defined in the EditorGui class is a truly generic editor."); System.out.println("It accepts an argument of type ItemEditor, and delegates"); System.out.println(" all editing tasks to its ItemEditor and the associated GUI."); System.out.println(" The getEditor() Factory Method is used to oBTain the ItemEditor"); System.out.println(" for the example."); System.out.println(); System.out.println("Notice that the editor in the top portion of the GUI is,"); System.out.println(" in fact, returned by the ItemEditor belonging to the"); System.out.println(" Contact class, and has appropriate fields for that class."); EditorGui runner = new EditorGui(someone.getEditor()); runner.createGui(); } } class EditorGui implements ActionListener{ private JFrame mainFrame; private JTextArea display; private JButton update, exit; private JPanel controlPanel, displayPanel, editorPanel; private ItemEditor editor; public EditorGui(ItemEditor edit){ editor = edit; } public void createGui(){ mainFrame = new JFrame("Factory Pattern Example"); Container content = mainFrame.getContentPane(); content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS)); editorPanel = new JPanel(); editorPanel.add(editor.getGUI()); content.add(editorPanel); displayPanel = new JPanel(); display = new JTextArea(10, 40); display.setEditable(false); displayPanel.add(display); content.add(displayPanel); controlPanel = new JPanel(); update = new JButton("Update Item"); exit = new JButton("Exit"); controlPanel.add(update); controlPanel.add(exit); content.add(controlPanel); update.addActionListener(this); exit.addActionListener(this); mainFrame.addWindowListener(new WindowCloseManager()); mainFrame.pack(); mainFrame.setVisible(true); } public void actionPerformed(ActionEvent evt){ Object originator = evt.getSource(); if (originator == update){ updateItem(); } else if (originator == exit){ exitApplication(); } } private class WindowCloseManager extends WindowAdapter{ public void windowClosing(WindowEvent evt){ exitApplication(); } } private void updateItem(){ editor.commitChanges(); display.setText(editor.toString()); } private void exitApplication(){ System.exit(0); } }