dart_in_action/30_design_pattern_mediator....

40 lines
1.1 KiB
Dart
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
中介者模式Mediator Pattern
意图:用一个中介对象来封装一系列的对象交互,中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
主要解决:对象与对象之间存在大量的关联关系,这样势必会导致系统的结构变得很复杂,同时若一个对象发生改变,我们也需要跟踪与之相关联的对象,同时做出相应的处理。
何时使用:多个类相互耦合,形成了网状结构。
如何解决:将上述网状结构分离为星型结构。
*/
main(List<String> args) {
User robert = User("Robert");
User john = User("John");
robert.sendMessage("Hi! John!");
john.sendMessage("Hello! Robert!");
}
//////////////////////////////////////////////////////////////////
///
/// 创建中介类
///
class ChatRoom {
static void showMessage(User user, String message) {
print("[${user.name}]: $message");
}
}
///
/// 创建 user 类
///
class User {
String name;
User(this.name);
void sendMessage(String message) {
ChatRoom.showMessage(this, message);
}
}