6中介者模式
用一个中介对象封装一系列的对象的交互,中介者使各对象不需要显示的相互作用,从而使其耦合松散,而且可以独立的改变他们之间的交互。 就是将所有需要交互的对象,传递给中介者, 通过中介者来实现各个对象交互过程.
1.来个学生抽象类
public abstract class Student {
String name;
int age;
abstract void study();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
2.来个jeck的具体学生类
public class JeckStudent extends Student {
private static final String TAG = "JeckStudent";
public JeckStudent(String name,int age) {
super.name = name;
super.age =age;
}
@Override
void study() {
Log.e(TAG, "study: "+name+age );
}
}
3.来个tom的具体学生
public class TomStudent extends Student {
private static final String TAG = "TomStudent";
public TomStudent(String name,int age) {
super.name = name;
super.age =age;
}
@Override
void study() {
Log.e(TAG, "study: " + name + " "+age);
}
}
4.中介者的抽象类,拿到其他多个学生对象
public abstract class Mediator {
Student studentA;
Student studentB;
public void setStudentA(Student studentA) {
this.studentA = studentA;
}
public void setStudentB(Student studentB) {
this.studentB = studentB;
}
public abstract void MediatorDoSomething();
}
5.具体实现中介对象,运行中介持有对象实现功能.
public class ConcreteMediator extends Mediator {
@Override
public void MediatorDoSomething() {
super.studentA.study();
super.studentB.study();
}
}
6.测试方法
public class Test {
public void test() {
Mediator mediator = new ConcreteMediator();
Student studentTom = new TomStudent("tom",11);
Student studentJeck = new JeckStudent("jeck",12);
mediator.setStudentA(studentTom);
mediator.setStudentB(studentJeck);
mediator.MediatorDoSomething();
}
}