/**
* @version 1.00 11 Mar 1997
* @author Cay Horstmann
*/
public class PropertyTest {
public static void main(String[] args) {
Employee harry = new Employee("Harry Hacker", 35000);
Employee carl = new Employee("Carl Cracker", 75000);
PropertyEditor editor = new PropertyEditor(new Property[] {
harry.getSalaryProperty(), harry.getSalaryProperty(),
carl.getSalaryProperty(), carl.getSeniorityProperty() });
System.out.println("Before:");
harry.print();
carl.print();
System.out.println("Edit properties:");
editor.editProperties();
System.out.println("After:");
harry.print();
carl.print();
}
}
interface Property {
public String get();
public void set(String s);
public String name();
}
class PropertyEditor {
public PropertyEditor(Property[] p) {
properties = p;
}
public void editProperties() {
while (true) {
for (int i = 0; i < properties.length; i++)
System.out.println((i + 1) + ":" + properties[i].name() + "="
+ properties[i].get());
//set new value for second
String value = "10";
properties[2 - 1].set(value);
}
}
private Property[] properties;
}
class Employee {
public Employee(String n, double s) {
name = n;
salary = s;
}
public void print() {
System.out.println(name + " " + salary + " ");
}
public void raiseSalary(double byPercent) {
salary *= 1 + byPercent / 100;
}
private class SalaryProperty implements Property {
public String name() {
return name + "'s salary";
}
public String get() {
return "" + salary;
}
public void set(String s) {
if (isSet)
return; // can set once
double sal = Double.parseDouble(s);
if (sal > 0) {
salary = sal;
isSet = true;
}
}
private boolean isSet = false;
}
public Property getSalaryProperty() {
return new SalaryProperty();
}
private class SeniorityProperty implements Property {
public String name() {
return name + "'s years on the job";
}
public String get() {
return "20";
}
public void set(String s) {
} // can't set seniority
}
public Property getSeniorityProperty() {
return new SeniorityProperty();
}
private String name;
private double salary;
}
|