/**
* @Author: king
* @Date: 2019/12/24 21:20
* @Version 1.0
* 抽象主题
*/
public interface Subject {
public void addObserver(Observer observer);
public void deleteObserver(Observer observer);
public void nofityObservers();
}
/**
* @Author: king
* @Date: 2019/12/24 21:21
* @Version 1.0
* 抽象观察者
*/
public interface Observer {
public void hearTel(String msg);
}
import java.util.ArrayList;
/**
* @Author: king
* @Date: 2019/12/25 9:32
* @Version 1.0
* 具体主题
*/
public class SeekJobCenter implements Subject {
String msg;
boolean changed;
ArrayList<Observer> personList;
SeekJobCenter() {
personList = new ArrayList<Observer>();
msg = "";
changed = false;
}
public void addObserver(Observer observer) {
if (!personList.contains(observer)) {
personList.add(observer);
}
}
public void deleteObserver(Observer observer) {
if (personList.contains(observer)) {
personList.remove(observer);
}
}
public void nofityObservers() {
if (changed) {
for (int i = 0; i < personList.size(); i++) {
Observer observer = personList.get(i);
observer.hearTel(msg);
}
}
changed = false;
}
public void giveMsg(String str) {
if (str.equals(msg)) {
changed = false;
} else {
msg = str;
changed = true;
}
}
}
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
/**
* @Author: king
* @Date: 2019/12/25 9:53
* @Version 1.0
* 具体观察者-学生
*/
public class Student implements Observer {
Subject subject;
File file;
Student(Subject subject, String filename) {
this.subject = subject;
subject.addObserver(this);
file = new File(filename);
}
public void hearTel(String msg) {
try {
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
randomAccessFile.seek(randomAccessFile.length());//设置文件指针位置
byte[] bytes = msg.getBytes();
randomAccessFile.write(bytes);
System.out.print("我是学生,");
System.out.println("我向文件" + file.getName() + "写入:");
System.out.println(msg);
} catch (FileNotFoundException e) {
System.out.println("文件未找到");
} catch (IOException e) {
System.out.println("IO异常");
}
}
}
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
/**
* @Author: king
* @Date: 2019/12/25 10:32
* @Version 1.0
* 具体观察者-员工
*/
public class Custom implements Observer {
Subject subject;
File file;
Custom(Subject subject, String filename) {
this.subject = subject;
subject.addObserver(this);
file = new File(filename);
}
public void hearTel(String msg) {
try {
boolean b = msg.contains("java程序员") || msg.contains("软件工程师");
if (b) {
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
randomAccessFile.seek(randomAccessFile.length());//设置文件指针位置
byte[] bytes = msg.getBytes();
randomAccessFile.write(bytes);
System.out.print("我是员工,");
System.out.println("我向文件" + file.getName() + "写入:");
System.out.println(msg);
} else {
System.out.println("没有有用的信息");
}
} catch (FileNotFoundException e) {
System.out.println("文件未找到");
} catch (IOException e) {
System.out.println("IO异常");
}
}
}