中介者模式
中介者模式也是用来降低类类之间的耦合的。如果类和类之间有依赖关系的话,只要修改一个对象,其它关联的对象都得进行修改,这不利于功能的拓展和维护。而使用中介者模式,只需关心和Mediator类的关系,具体类和类之间的关系及调度交给Mediator就可以
UML
Java
- 定义Mediator接口,提供对外操作的方法定义:
public interface Mediator { void createMediator(); void workAll(); }
- 定义User接口:
public abstract class User { private final Mediator mediator; public Mediator getMediator() { return mediator; } public User(Mediator mediator) { this.mediator = mediator; } public abstract void work(); }
- 实现User1, User2:
public class User1 extends User { public User1(Mediator mediator) { super(mediator); } @Override public void work() { System.out.println("user1 exe!"); } } public class User2 extends User { public User2(Mediator mediator) { super(mediator); } @Override public void work() { System.out.println("user2 exe!"); } }
- 实现MyMediator类,里面持有User1和User2的实例,用来实现对User1和User2的控制。这样User1和User2两个对象相互独立,他们只需要保持好和Mediator之间的关系:
public class MyMediator implements Mediator { private User user1; private User user2; public User getUser1() { return user1; } public User getUser2() { return user2; } @Override public void createMediator() { user1 = new User1(this); user2 = new User2(this); } @Override public void workAll() { user1.work(); user2.work(); } }
- 测试代码:
public class MediatorTest { public static void main(String[] args) { Mediator mediator = new MyMediator(); mediator.createMediator(); mediator.workAll(); } }
- 测试结果:
user1 exe! user2 exe!
CLOS
- 使用辅助方法来实现方法编排:
(defclass user () ()) (defmethod work ((u user)) '()) (defmethod work :before ((u user)) (format t "user1 exe! ~C" #\linefeed)) (defmethod work :after ((u user)) (format t "user2 exe! ~C" #\linefeed))
- 测试:
(work (make-instance 'user)) ;; user1 exe! ;; user2 exe! ;; => NIL