[2]
DejaVU Online:
Principles of Object-Oriented Software Development
(©)
Taking our view of a person as an actor as a starting point, we need first to establish the repertoire of possible behavior.
class actor { actor
public static final int Person = 0;
public static final int Student = 1;
public static final int Employer = 2;
public static final int Final = 3;
public void walk() { if (exists()) self().walk(); }
public void talk() { if (exists()) self().talk(); }
public void think() { if (exists()) self().think(); }
public void act() { if (exists()) self().act(); }
public boolean exists() { return false; }
public actor self() { return this; }
public void become(actor A) { }
public void become(int R) { }
};
Next, we may wish to refine the behavior of an actor for certain roles, such as for example the student and employer roles, which are among the many roles a person can play.
class student extends actor { student
public void talk() { System.out.println("OOP"); }
public void think() { System.out.println("Z"); }
};
class employer extends actor { employer
public void talk() { System.out.println("money"); }
public void act() { System.out.println("business"); }
};
class person extends actor { person
public person() {
role = new actor[ Final+1 ];
for( int i = Person; i <= Final; i++ ) role[i]=this;
become(Person);
}
public boolean exists() { return role[_role] != this; }
public actor self() {
if ( role[ Person ] != this ) return role[ Person ].self();
else return role[_role];
}
public void become(actor p) { role[ Person ] = p; }
public void become(int R) {
if (role[ Person ] != this) self().become(R);
else {
_role = R;
if ( role[_role] == this ) {
switch(_role) {
case Person: break; // nothing changes
case Student: role[_role] = new student(); break;
case Employer: role[_role] = new employer(); break;
case Final: role[_role] = new actor(); break;
default: break; // nothing happens
}
}
}
}
int _role;
actor role[];
};
Assuming or `becoming' a role results in creating a role instance if none exists and setting the _role instance variable to that particular role. When a person's identity has been changed, assuming a role affects the actor that replaced the person's original identity. (However, only a person can change roles!)
The ability to become an actor allows us to model the various phases of a person's lifetime by different classes, as illustrated by the adult class.
class adult extends person { adult
public void talk() { System.out.println("interesting"); }
};
public class go { example
public static void main(String[] args) {
person p = new person(); p.talk(); empty
p.become(actor.Student); p.talk(); OOP
p.become(actor.Employer); p.talk(); money
p.become(new adult()); p.talk(); interesting
p.become(actor.Student); p.talk(); OOP
p.become(p); p.talk(); old role: employer
p.become(actor.Person); p.talk(); // initial state
}
};
|
Hush Online Technology
hush@cs.vu.nl
12/29/99 |
|
|