两个类 一个是主播 Anchor 一个是嘉宾 Guest 主播说话的时候,嘉宾要停下,嘉宾只能在主播不说话的时候说话。
package action.mediator1;
public class Anchor {
private boolean free;
private Mediator med;
public Anchor(Mediator md){
med=md;
}
public boolean isFree() {
return free;
}
public void setFree(boolean free) {
this.free = free;
}
public void speak() {
med.anchorSpeak();
}
public void stop() {
med.anchorStop();
}
}
package action.mediator1;
public class Guest {
private boolean free;
private Mediator med;
public Guest(Mediator md) {
this.med = md;
}
public boolean isFree() {
return free;
}
public void setFree(boolean free) {
this.free = free;
}
public void speak() {
med.guestSpeak();
}
public void stop() {
med.guestStop();
}
}
package action.mediator1;
public class Mediator {
private Anchor anchor;
private Guest guest;
public void regAnchor(Anchor anchor){
this.anchor=anchor;
}
public void regGuest(Guest guest){
this.guest=guest;
}
public void anchorSpeak(){
if(!guest.isFree()){
guest.stop();
}
System.out.println("Anchor is speaking....");
anchor.setFree(false);
}
public void guestSpeak(){
if(anchor.isFree()){
System.out.println("Guest is speaking....");
guest.setFree(false);
}
else{
System.out.println("Anchor is speaking. Do not interrupt...");
}
}
public void anchorStop(){
System.out.println("Anchor stop speaking now....");
anchor.setFree(true);
}
public void guestStop(){
System.out.println("Guest stop speaking now...");
guest.setFree(true);
}
}
package action.mediator1;
public class Demo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Mediator med = new Mediator();
Anchor anchor = new Anchor(med);
Guest guest=new Guest(med);
med.regAnchor(anchor);
med.regGuest(guest);
anchor.speak();
guest.speak();
anchor.stop();
guest.speak();
anchor.speak();
}
}