您的位置:首页 > 编程语言 > Java开发

java设计模式之中介者模式

2014-09-19 16:41 330 查看
1.mediator:此抽象类用来定义中介者,同时要定义一个接口方法,以便和其他同事对象进行交互:

package com.mediator.example;

public abstract class Mediator {

public abstract void notice(String content);

}

2.mediatorImpl:此类用来实现mediator,然后此类要保留同事对象的引用,这些的话,才能方便他们之间的交互:

package com.mediator.example;

import com.mediator.object.Dog;

import com.mediator.object.Sheep;

public class MediatorImpl extends Mediator {

private Dog dog;

private Sheep sheep;

public MediatorImpl() {

dog = new Dog();

sheep = new Sheep();

}

@Override

public void notice(String content) {

if (content.equals("bone"))

dog.eat();

if (content.equals("grass"))

sheep.eat();

}

}

3.接下来便是同事对象类,此处我们采用面向接口编程的思想,其体程序如下:

3.1:

package com.mediator.object;

public interface Animal {

public void eat();

}

3.2:

package com.mediator.object;

public class Dog implements Animal {

@Override

public void eat() {

System.out.println("the dog is eating the bone......");

}

}

3.3:

package com.mediator.object;

public class Sheep implements Animal {

@Override

public void eat() {

System.out.println("the sheep is eating the grass......");

}

}

4.测试程序如下所示:

package com.mediator.test;

import com.mediator.example.Mediator;

import com.mediator.example.MediatorImpl;

public class Test {

public static void main(String[] args) {

Mediator m = new MediatorImpl();

System.out.println("the result of bone:");

m.notice("bone");

System.out.println("\n");

System.out.println("the result of grass:");

m.notice("grass");

}

}

5.运行结果如下所示:

the result of bone:

the dog is eating the bone......

the result of grass:

the sheep is eating the grass......

总结:中介者模式主要是通过中介者,在中介者处根据一些条件来进行相应的判断,然后才和对应的同事对象进行交互。而且此处定义同事对象的时候,我们是用面向接口编程的思想的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: