一:观察者模式又可称为发布/订阅(Publish/Subscribe)模式,例如今天发工资了,大家手机都来短信通知了,快看啊,600.~,当到发工资的时候,会自动推送消息到每个人,假如你离职了,财务可以把你的手机移除,有新人入职,又可以添加.还可以给你涨工资601.
public interface Salary {
//发送短信通知
void sendmessage();
//不给离职人员发
void removeEmp(Employees employees);
//给新入职人员发
void addEmp(Employees employees);
}
public interface Employees {
public void receive(String salrayNum);
}
public class Boss implements Salary {
List<Employees> emp = new ArrayList<>();
String salaryNum;
@Override
public void removeEmp(Employees employees) {
int i = emp.indexOf(employees);
if (i>=0) {
emp.remove(employees);
System.out.println("老板移除了:"+((Employee)employees).name);
}
}
@Override
public void addEmp(Employees employees) {
emp.add(employees);
}
@Override
public void sendmessage() {
for (int i = 0; i < emp.size(); i++) {
emp.get(i).receive(salaryNum);
}
}
public void changeSalary(String salaryNum){
this.salaryNum = salaryNum;
System.out.println("老板发了"+salaryNum+"钱");
this.sendmessage();
}
}
public class Employee implements Employees {
public Boss boss;
public String name;
public String getName() {
return name;
}
public Employee(String name,Boss boss) {
this.name=name;
this.boss=boss;
boss.addEmp(this);
}
@Override
public void receive(String salaryNum) {
System.out.println(this.name+"收到了:"+salaryNum+"钱");
}
}
public class Test {
@SuppressWarnings("unused")
public static void main(String[] args) {
Boss boss = new Boss();
Employees A = new Employee("A", boss);
Employees B = new Employee("B", boss);
Employees C = new Employee("C", boss);
//boss.removeEmp(A);
boss.changeSalary("500");
}
//老板发了500钱
A收到了:500钱
B收到了:500钱
C收到了:500钱
//老板移除了:A
老板发了500钱
B收到了:500钱
C收到了:500钱
}