Java/Design Pattern/Visitor Pattern
Visitor Pattern 1
<source lang="java">
//[C] 2002 Sun Microsystems, Inc.--- import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Iterator; public class RunVisitorPattern {
public static void main(String[] arguments) { System.out.println("Example for the Visitor pattern"); System.out.println(); System.out .println("This sample will use a ProjectCostVisitor to calculate"); System.out.println(" the total amount required to complete a Project."); System.out.println(); System.out.println("Deserializing a test Project for Visitor pattern"); System.out.println(); if (!(new File("data.ser").exists())) { DataCreator.serialize("data.ser"); } Project project = (Project) (DataRetriever.deserializeData("data.ser")); System.out .println("Creating a ProjectCostVisitor, to calculate the total cost of the project."); ProjectCostVisitor visitor = new ProjectCostVisitor(); visitor.setHourlyRate(100); System.out .println("Moving throuhg the Project, calculating total cost"); System.out .println(" by passing the Visitor to each of the ProjectItems."); visitProjectItems(project, visitor); System.out.println("The total cost for the project is: " + visitor.getTotalCost()); } private static void visitProjectItems(ProjectItem item, ProjectVisitor visitor) { item.accept(visitor); if (item.getProjectItems() != null) { Iterator subElements = item.getProjectItems().iterator(); while (subElements.hasNext()) { visitProjectItems((ProjectItem) subElements.next(), visitor); } } }
} interface Contact extends Serializable {
public static final String SPACE = " "; public String getFirstName(); public String getLastName(); public String getTitle(); public String getOrganization(); public void setFirstName(String newFirstName); public void setLastName(String newLastName); public void setTitle(String newTitle); public void setOrganization(String newOrganization);
} class Task implements ProjectItem {
private String name; private ArrayList projectItems = new ArrayList(); private Contact owner; private double timeRequired; public Task() { } public Task(String newName, Contact newOwner, double newTimeRequired) { name = newName; owner = newOwner; timeRequired = newTimeRequired; } public String getName() { return name; } public ArrayList getProjectItems() { return projectItems; } public Contact getOwner() { return owner; } public double getTimeRequired() { return timeRequired; } public void setName(String newName) { name = newName; } public void setOwner(Contact newOwner) { owner = newOwner; } public void setTimeRequired(double newTimeRequired) { timeRequired = newTimeRequired; } public void addProjectItem(ProjectItem element) { if (!projectItems.contains(element)) { projectItems.add(element); } } public void removeProjectItem(ProjectItem element) { projectItems.remove(element); } public void accept(ProjectVisitor v) { v.visitTask(this); }
} class Deliverable implements ProjectItem {
private String name; private String description; private Contact owner; private double materialsCost; private double productionCost; public Deliverable() { } public Deliverable(String newName, String newDescription, Contact newOwner, double newMaterialsCost, double newProductionCost) { name = newName; description = newDescription; owner = newOwner; materialsCost = newMaterialsCost; productionCost = newProductionCost; } public String getName() { return name; } public String getDescription() { return description; } public Contact getOwner() { return owner; } public double getMaterialsCost() { return materialsCost; } public double getProductionCost() { return productionCost; } public void setMaterialsCost(double newCost) { materialsCost = newCost; } public void setProductionCost(double newCost) { productionCost = newCost; } public void setName(String newName) { name = newName; } public void setDescription(String newDescription) { description = newDescription; } public void setOwner(Contact newOwner) { owner = newOwner; } public void accept(ProjectVisitor v) { v.visitDeliverable(this); } public ArrayList getProjectItems() { return null; }
} interface ProjectVisitor {
public void visitDependentTask(DependentTask p); public void visitDeliverable(Deliverable p); public void visitTask(Task p); public void visitProject(Project p);
} interface ProjectItem extends Serializable {
public void accept(ProjectVisitor v); public ArrayList getProjectItems();
} class ContactImpl implements Contact {
private String firstName; private String lastName; private String title; private String organization; public ContactImpl() { } public ContactImpl(String newFirstName, String newLastName, String newTitle, String newOrganization) { firstName = newFirstName; lastName = newLastName; title = newTitle; organization = newOrganization; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public String getTitle() { return title; } public String getOrganization() { return organization; } public void setFirstName(String newFirstName) { firstName = newFirstName; } public void setLastName(String newLastName) { lastName = newLastName; } public void setTitle(String newTitle) { title = newTitle; } public void setOrganization(String newOrganization) { organization = newOrganization; } public String toString() { return firstName + SPACE + lastName; }
} class DataCreator {
private static final String DEFAULT_FILE = "data.ser"; public static void main(String[] args) { String fileName; if (args.length == 1) { fileName = args[0]; } else { fileName = DEFAULT_FILE; } serialize(fileName); } public static void serialize(String fileName) { try { serializeToFile(createData(), fileName); } catch (IOException exc) { exc.printStackTrace(); } } private static Serializable createData() { Contact contact = new ContactImpl("Test", "Subject", "Volunteer", "United Patterns Consortium"); Project project = new Project("Project 1", "Test Project"); Task task1 = new Task("Task 1", contact, 1); Task task2 = new Task("Task 2", contact, 1); project.addProjectItem(new Deliverable("Deliverable 1", "Layer 1 deliverable", contact, 50.0, 50.0)); project.addProjectItem(task1); project.addProjectItem(task2); project.addProjectItem(new DependentTask("Dependent Task 1", contact, 1, 1)); Task task3 = new Task("Task 3", contact, 1); Task task4 = new Task("Task 4", contact, 1); Task task5 = new Task("Task 5", contact, 1); Task task6 = new Task("Task 6", contact, 1); DependentTask dtask2 = new DependentTask("Dependent Task 2", contact, 1, 1); task1.addProjectItem(task3); task1.addProjectItem(task4); task1.addProjectItem(task5); task1.addProjectItem(dtask2); dtask2.addDependentTask(task5); dtask2.addDependentTask(task6); dtask2.addProjectItem(new Deliverable("Deliverable 2", "Layer 3 deliverable", contact, 50.0, 50.0)); task3.addProjectItem(new Deliverable("Deliverable 3", "Layer 3 deliverable", contact, 50.0, 50.0)); task4.addProjectItem(new Task("Task 7", contact, 1)); task4.addProjectItem(new Deliverable("Deliverable 4", "Layer 3 deliverable", contact, 50.0, 50.0)); return project; } private static void serializeToFile(Serializable content, String fileName) throws IOException { ObjectOutputStream serOut = new ObjectOutputStream( new FileOutputStream(fileName)); serOut.writeObject(content); serOut.close(); }
} class DataRetriever {
public static Object deserializeData(String fileName) { Object returnValue = null; try { File inputFile = new File(fileName); if (inputFile.exists() && inputFile.isFile()) { ObjectInputStream readIn = new ObjectInputStream( new FileInputStream(fileName)); returnValue = readIn.readObject(); readIn.close(); } else { System.err.println("Unable to locate the file " + fileName); } } catch (ClassNotFoundException exc) { exc.printStackTrace(); } catch (IOException exc) { exc.printStackTrace(); } return returnValue; }
} class DependentTask extends Task {
private ArrayList dependentTasks = new ArrayList(); private double dependencyWeightingFactor; public DependentTask() { } public DependentTask(String newName, Contact newOwner, double newTimeRequired, double newWeightingFactor) { super(newName, newOwner, newTimeRequired); dependencyWeightingFactor = newWeightingFactor; } public ArrayList getDependentTasks() { return dependentTasks; } public double getDependencyWeightingFactor() { return dependencyWeightingFactor; } public void setDependencyWeightingFactor(double newFactor) { dependencyWeightingFactor = newFactor; } public void addDependentTask(Task element) { if (!dependentTasks.contains(element)) { dependentTasks.add(element); } } public void removeDependentTask(Task element) { dependentTasks.remove(element); } public void accept(ProjectVisitor v) { v.visitDependentTask(this); }
} class Project implements ProjectItem {
private String name; private String description; private ArrayList projectItems = new ArrayList(); public Project() { } public Project(String newName, String newDescription) { name = newName; description = newDescription; } public String getName() { return name; } public String getDescription() { return description; } public ArrayList getProjectItems() { return projectItems; } public void setName(String newName) { name = newName; } public void setDescription(String newDescription) { description = newDescription; } public void addProjectItem(ProjectItem element) { if (!projectItems.contains(element)) { projectItems.add(element); } } public void removeProjectItem(ProjectItem element) { projectItems.remove(element); } public void accept(ProjectVisitor v) { v.visitProject(this); }
} class ProjectCostVisitor implements ProjectVisitor {
private double totalCost; private double hourlyRate; public double getHourlyRate() { return hourlyRate; } public double getTotalCost() { return totalCost; } public void setHourlyRate(double rate) { hourlyRate = rate; } public void resetTotalCost() { totalCost = 0.0; } public void visitDependentTask(DependentTask p) { double taskCost = p.getTimeRequired() * hourlyRate; taskCost *= p.getDependencyWeightingFactor(); totalCost += taskCost; } public void visitDeliverable(Deliverable p) { totalCost += p.getMaterialsCost() + p.getProductionCost(); } public void visitTask(Task p) { totalCost += p.getTimeRequired() * hourlyRate; } public void visitProject(Project p) { }
}
</source>
Visitor Pattern - Example
<source lang="java">
/* Software Architecture Design Patterns in Java by Partha Kuchana Auerbach Publications
- /
import java.awt.BorderLayout; import java.awt.Container; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.Vector; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.UIManager; import com.sun.java.swing.plaf.windows.WindowsLookAndFeel; public class OrderManager extends JFrame {
public static final String newline = "\n"; public static final String GET_TOTAL = "Get Total"; public static final String CREATE_ORDER = "Create Order"; public static final String EXIT = "Exit"; public static final String CA_ORDER = "California Order"; public static final String NON_CA_ORDER = "Non-California Order"; public static final String OVERSEAS_ORDER = "Overseas Order"; private JComboBox cmbOrderType; private JTextField txtOrderAmount, txtAdditionalTax, txtAdditionalSH; private JLabel lblOrderType, lblOrderAmount; private JLabel lblAdditionalTax, lblAdditionalSH; private JLabel lblTotal, lblTotalValue; private OrderVisitor objVisitor; public OrderManager() { super("Visitor Pattern - Example"); //Create the visitor instance objVisitor = new OrderVisitor(); cmbOrderType = new JComboBox(); cmbOrderType.addItem(OrderManager.CA_ORDER); cmbOrderType.addItem(OrderManager.NON_CA_ORDER); cmbOrderType.addItem(OrderManager.OVERSEAS_ORDER); txtOrderAmount = new JTextField(10); txtAdditionalTax = new JTextField(10); txtAdditionalSH = new JTextField(10); lblOrderType = new JLabel("Order Type:"); lblOrderAmount = new JLabel("Order Amount:"); lblAdditionalTax = new JLabel("Additional Tax(CA Orders Only):"); lblAdditionalSH = new JLabel("Additional S & H(Overseas Orders Only):"); lblTotal = new JLabel("Result:"); lblTotalValue = new JLabel("Click Create or GetTotal Button"); //Create the open button JButton getTotalButton = new JButton(OrderManager.GET_TOTAL); getTotalButton.setMnemonic(KeyEvent.VK_G); JButton createOrderButton = new JButton(OrderManager.CREATE_ORDER); getTotalButton.setMnemonic(KeyEvent.VK_C); JButton exitButton = new JButton(OrderManager.EXIT); exitButton.setMnemonic(KeyEvent.VK_X); ButtonHandler objButtonHandler = new ButtonHandler(this); getTotalButton.addActionListener(objButtonHandler); createOrderButton.addActionListener(objButtonHandler); exitButton.addActionListener(new ButtonHandler()); //For layout purposes, put the buttons in a separate panel JPanel buttonPanel = new JPanel(); JPanel panel = new JPanel(); GridBagLayout gridbag2 = new GridBagLayout(); panel.setLayout(gridbag2); GridBagConstraints gbc2 = new GridBagConstraints(); panel.add(getTotalButton); panel.add(createOrderButton); panel.add(exitButton); gbc2.anchor = GridBagConstraints.EAST; gbc2.gridx = 0; gbc2.gridy = 0; gridbag2.setConstraints(createOrderButton, gbc2); gbc2.gridx = 1; gbc2.gridy = 0; gridbag2.setConstraints(getTotalButton, gbc2); gbc2.gridx = 2; gbc2.gridy = 0; gridbag2.setConstraints(exitButton, gbc2); //**************************************************** GridBagLayout gridbag = new GridBagLayout(); buttonPanel.setLayout(gridbag); GridBagConstraints gbc = new GridBagConstraints(); buttonPanel.add(lblOrderType); buttonPanel.add(cmbOrderType); buttonPanel.add(lblOrderAmount); buttonPanel.add(txtOrderAmount); buttonPanel.add(lblAdditionalTax); buttonPanel.add(txtAdditionalTax); buttonPanel.add(lblAdditionalSH); buttonPanel.add(txtAdditionalSH); buttonPanel.add(lblTotal); buttonPanel.add(lblTotalValue); gbc.insets.top = 5; gbc.insets.bottom = 5; gbc.insets.left = 5; gbc.insets.right = 5; gbc.anchor = GridBagConstraints.EAST; gbc.gridx = 0; gbc.gridy = 0; gridbag.setConstraints(lblOrderType, gbc); gbc.anchor = GridBagConstraints.WEST; gbc.gridx = 1; gbc.gridy = 0; gridbag.setConstraints(cmbOrderType, gbc); gbc.anchor = GridBagConstraints.EAST; gbc.gridx = 0; gbc.gridy = 1; gridbag.setConstraints(lblOrderAmount, gbc); gbc.anchor = GridBagConstraints.WEST; gbc.gridx = 1; gbc.gridy = 1; gridbag.setConstraints(txtOrderAmount, gbc); gbc.anchor = GridBagConstraints.EAST; gbc.gridx = 0; gbc.gridy = 2; gridbag.setConstraints(lblAdditionalTax, gbc); gbc.anchor = GridBagConstraints.WEST; gbc.gridx = 1; gbc.gridy = 2; gridbag.setConstraints(txtAdditionalTax, gbc); gbc.anchor = GridBagConstraints.EAST; gbc.gridx = 0; gbc.gridy = 3; gridbag.setConstraints(lblAdditionalSH, gbc); gbc.anchor = GridBagConstraints.WEST; gbc.gridx = 1; gbc.gridy = 3; gridbag.setConstraints(txtAdditionalSH, gbc); gbc.anchor = GridBagConstraints.EAST; gbc.gridx = 0; gbc.gridy = 4; gridbag.setConstraints(lblTotal, gbc); gbc.anchor = GridBagConstraints.WEST; gbc.gridx = 1; gbc.gridy = 4; gridbag.setConstraints(lblTotalValue, gbc); gbc.insets.left = 2; gbc.insets.right = 2; gbc.insets.top = 40; //**************************************************** //Add the buttons and the log to the frame Container contentPane = getContentPane(); contentPane.add(buttonPanel, BorderLayout.NORTH); contentPane.add(panel, BorderLayout.CENTER); try { UIManager.setLookAndFeel(new WindowsLookAndFeel()); SwingUtilities.updateComponentTreeUI(OrderManager.this); } catch (Exception ex) { System.out.println(ex); } } public static void main(String[] args) { JFrame frame = new OrderManager(); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); //frame.pack(); frame.setSize(500, 400); frame.setVisible(true); } public void setTotalValue(String msg) { lblTotalValue.setText(msg); } public OrderVisitor getOrderVisitor() { return objVisitor; } public String getOrderType() { return (String) cmbOrderType.getSelectedItem(); } public String getOrderAmount() { return txtOrderAmount.getText(); } public String getTax() { return txtAdditionalTax.getText(); } public String getSH() { return txtAdditionalSH.getText(); }
} // End of class OrderManager class ButtonHandler implements ActionListener {
OrderManager objOrderManager; public void actionPerformed(ActionEvent e) { String totalResult = null; if (e.getActionCommand().equals(OrderManager.EXIT)) { System.exit(1); } if (e.getActionCommand().equals(OrderManager.CREATE_ORDER)) { //get input values String orderType = objOrderManager.getOrderType(); String strOrderAmount = objOrderManager.getOrderAmount(); String strTax = objOrderManager.getTax(); String strSH = objOrderManager.getSH(); double dblOrderAmount = 0.0; double dblTax = 0.0; double dblSH = 0.0; if (strOrderAmount.trim().length() == 0) { strOrderAmount = "0.0"; } if (strTax.trim().length() == 0) { strTax = "0.0"; } if (strSH.trim().length() == 0) { strSH = "0.0"; } dblOrderAmount = new Double(strOrderAmount).doubleValue(); dblTax = new Double(strTax).doubleValue(); dblSH = new Double(strSH).doubleValue(); //Create the order Order order = createOrder(orderType, dblOrderAmount, dblTax, dblSH); //Get the Visitor OrderVisitor visitor = objOrderManager.getOrderVisitor(); // accept the visitor instance order.accept(visitor); objOrderManager.setTotalValue(" Order Created Successfully"); } if (e.getActionCommand().equals(OrderManager.GET_TOTAL)) { //Get the Visitor OrderVisitor visitor = objOrderManager.getOrderVisitor(); totalResult = new Double(visitor.getOrderTotal()).toString(); totalResult = " Orders Total = " + totalResult; objOrderManager.setTotalValue(totalResult); } } public Order createOrder(String orderType, double orderAmount, double tax, double SH) { if (orderType.equalsIgnoreCase(OrderManager.CA_ORDER)) { return new CaliforniaOrder(orderAmount, tax); } if (orderType.equalsIgnoreCase(OrderManager.NON_CA_ORDER)) { return new NonCaliforniaOrder(orderAmount); } if (orderType.equalsIgnoreCase(OrderManager.OVERSEAS_ORDER)) { return new OverseasOrder(orderAmount, SH); } return null; } public ButtonHandler() { } public ButtonHandler(OrderManager inObjOrderManager) { objOrderManager = inObjOrderManager; }
} // End of class ButtonHandler class NonCaliforniaOrder implements Order {
private double orderAmount; public NonCaliforniaOrder() { } public NonCaliforniaOrder(double inp_orderAmount) { orderAmount = inp_orderAmount; } public double getOrderAmount() { return orderAmount; } public void accept(OrderVisitor v) { v.visit(this); }
} class CaliforniaOrder implements Order {
private double orderAmount; private double additionalTax; public CaliforniaOrder() { } public CaliforniaOrder(double inp_orderAmount, double inp_additionalTax) { orderAmount = inp_orderAmount; additionalTax = inp_additionalTax; } public double getOrderAmount() { return orderAmount; } public double getAdditionalTax() { return additionalTax; } public void accept(OrderVisitor v) { v.visit(this); }
} interface VisitorInterface {
public void visit(NonCaliforniaOrder nco); public void visit(CaliforniaOrder co); public void visit(OverseasOrder oo);
} class OverseasOrder implements Order {
private double orderAmount; private double additionalSH; public OverseasOrder() { } public OverseasOrder(double inp_orderAmount, double inp_additionalSH) { orderAmount = inp_orderAmount; additionalSH = inp_additionalSH; } public double getOrderAmount() { return orderAmount; } public double getAdditionalSH() { return additionalSH; } public void accept(OrderVisitor v) { v.visit(this); }
} class OrderVisitor implements VisitorInterface {
private Vector orderObjList; private double orderTotal; public OrderVisitor() { orderObjList = new Vector(); } public void visit(NonCaliforniaOrder inp_order) { orderTotal = orderTotal + inp_order.getOrderAmount(); } public void visit(CaliforniaOrder inp_order) { orderTotal = orderTotal + inp_order.getOrderAmount() + inp_order.getAdditionalTax(); } public void visit(OverseasOrder inp_order) { orderTotal = orderTotal + inp_order.getOrderAmount() + inp_order.getAdditionalSH(); } public double getOrderTotal() { return orderTotal; }
} interface Order {
public void accept(OrderVisitor v);
}
</source>
Visitor pattern in Java
<source lang="java">
/* The Design Patterns Java Companion Copyright (C) 1998, by James W. Cooper IBM Thomas J. Watson Research Center
- /
import java.awt.Color; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.Vector; import javax.swing.AbstractListModel; import javax.swing.Box; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; public class VacationDisplay extends JFrame implements ActionListener {
JawtList empList; JTextField total, btotal; JButton Vac; Employee[] employees; public VacationDisplay() { super("Vacation Display"); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); JPanel jp = new JPanel(); getContentPane().add(jp); jp.setLayout(new GridLayout(1, 2)); empList = new JawtList(10); jp.add(empList); createEmployees(); Box box = Box.createVerticalBox(); jp.add(box); total = new JTextField(5); total.setHorizontalAlignment(JTextField.CENTER); box.add(total); box.add(Box.createVerticalStrut(10)); btotal = new JTextField(5); btotal.setHorizontalAlignment(JTextField.CENTER); box.add(btotal); box.add(Box.createVerticalStrut(10)); Vac = new JButton("Vacations"); box.add(Vac); Vac.addActionListener(this); setSize(300, 200); setVisible(true); total.setText(" "); total.setBackground(Color.white); } public void createEmployees() { employees = new Employee[7]; int i = 0; employees[i++] = new Employee("Susan Bear", 55000, 12, 1); employees[i++] = new Employee("Adam Gehr", 150000, 9, 0); employees[i++] = new Employee("Fred Harris", 50000, 15, 2); employees[i++] = new Employee("David Oakley", 57000, 12, 2); employees[i++] = new Employee("Larry Thomas", 100000, 20, 6); Boss b = new Boss("Leslie Susi", 175000, 16, 4); b.setBonusDays(12); Boss b1 = new Boss("Laurence Byerly", 35000, 17, 6); b1.setBonusDays(17); employees[i++] = b; employees[i++] = b1; for (i = 0; i < employees.length; i++) { empList.add(employees[i].getName()); } } public void actionPerformed(ActionEvent e) { VacationVisitor vac = new VacationVisitor(); bVacationVisitor bvac = new bVacationVisitor(); for (int i = 0; i < employees.length; i++) { employees[i].accept(vac); employees[i].accept(bvac); } total.setText(new Integer(vac.getTotalDays()).toString()); btotal.setText(new Integer(bvac.getTotalDays()).toString()); } public static void main(String argv[]) { new VacationDisplay(); }
} class Employee {
int sickDays, vacDays; float Salary; String Name; public Employee(String name, float salary, int vacdays, int sickdays) { vacDays = vacdays; sickDays = sickdays; Salary = salary; Name = name; } public String getName() { return Name; } public int getSickdays() { return sickDays; } public int getVacDays() { return vacDays; } public float getSalary() { return Salary; } public void accept(Visitor v) { v.visit(this); }
} abstract class Visitor {
public abstract void visit(Employee emp); public abstract void visit(Boss emp);
} class Boss extends Employee {
private int bonusDays; public Boss(String name, float salary, int vacdays, int sickdays) { super(name, salary, vacdays, sickdays); } public void setBonusDays(int bonus) { bonusDays = bonus; } public int getBonusDays() { return bonusDays; } public void accept(Visitor v) { v.visit(this); }
} class VacationVisitor extends Visitor {
protected int total_days; public VacationVisitor() { total_days = 0; } public void visit(Employee emp) { total_days += emp.getVacDays(); } public void visit(Boss boss) { total_days += boss.getVacDays(); } public int getTotalDays() { return total_days; }
} class bVacationVisitor extends Visitor {
int total_days; public bVacationVisitor() { total_days = 0; } public int getTotalDays() { return total_days; } public void visit(Boss boss) { total_days += boss.getVacDays(); total_days += boss.getBonusDays(); } public void visit(Employee emp) { total_days += emp.getVacDays(); }
} //this is a simple adapter class to //convert List awt methods to Swing methods class JawtList extends JScrollPane implements ListSelectionListener, awtList {
private JList listWindow; private JListData listContents; public JawtList(int rows) { listContents = new JListData(); listWindow = new JList(listContents); listWindow.setPrototypeCellValue("Abcdefg Hijkmnop"); getViewport().add(listWindow); } public void add(String s) { listContents.addElement(s); } public void remove(String s) { listContents.removeElement(s); } public void clear() { listContents.clear(); } public String[] getSelectedItems() { Object[] obj = listWindow.getSelectedValues(); String[] s = new String[obj.length]; for (int i = 0; i < obj.length; i++) s[i] = obj[i].toString(); return s; } public void valueChanged(ListSelectionEvent e) { }
} class JListData extends AbstractListModel {
private Vector data; public JListData() { data = new Vector(); } public int getSize() { return data.size(); } public Object getElementAt(int index) { return data.elementAt(index); } public void addElement(String s) { data.addElement(s); fireIntervalAdded(this, data.size() - 1, data.size()); } public void removeElement(String s) { data.removeElement(s); fireIntervalRemoved(this, 0, data.size()); } public void clear() { int size = data.size(); data = new Vector(); fireIntervalRemoved(this, 0, size); }
} interface awtList {
public void add(String s); public void remove(String s); public String[] getSelectedItems();
}
</source>