跳至主要內容

中介者模式

约 566 字

中介者模式

核心思想

中介者模式迫使对象通过中介者进行通信,而不是直接相互引用,从而使其松散耦合,而且可以独立地改变它们之间的交互。

典型用例

聊天室

在聊天应用中,中介者可以充当消息传递的中心,控制和协调不同用户之间的消息交流。

在这个例子中,聊天室类是中介者,它管理所有的用户。每个用户都知道如何与中介者通信,发送消息时会通过中介者来间接发送给其他用户。这样,用户之间不直接通信,而是通过聊天室来协调,从而简化了对象间的交互。

// npm run code src/code/design-pattern/mediator/chat-room.ts

export {};

// 定义中介者接口
interface Mediator {
    registerUser(user: User): void;
    sendMessage(message: string, user: User): void;
}

interface User {
    send(message: string): void;
    receive(message: string): void;
}

// 创建具体中介者
class ChatRoom implements Mediator {
    private users: User[] = [];

    registerUser(user: User): void {
        this.users.push(user);
    }

    sendMessage(message: string, user: User): void {
        this.users.forEach(u => {
            if (u !== user) { // 发送给除了自己之外的所有用户
                u.receive(message);
            }
        });
    }
}

class ChatUser implements User {
    private name: string;
    private chatRoom: Mediator;

    constructor(name: string, chatRoom: Mediator) {
        this.name = name;
        this.chatRoom = chatRoom;
        this.chatRoom.registerUser(this);
    }

    send(message: string): void {
        console.log(`${this.name} sends: ${message}`);
        this.chatRoom.sendMessage(message, this);
    }

    receive(message: string): void {
        console.log(`${this.name} receives: ${message}`);
    }
}

const chatRoom = new ChatRoom();

const user1 = new ChatUser('Alice', chatRoom);
const user2 = new ChatUser('Bob', chatRoom);
const user3 = new ChatUser('Charlie', chatRoom);

user1.send("Hi there!");
user2.send("Hey!");
user3.send("Hello everyone!");

UI控件交互

中介者模式可以用来协调UI控件的交互,将控件的交互逻辑集中到一个中介者对象中,而不是让控件直接彼此通信。这样,控件只与中介者通信,中介者负责处理所有控件间的交互,这有助于降低复杂UI中控件的耦合度。

// npm run code src/code/design-pattern/mediator/ui-control-interaction.ts

export {};

interface Mediator {
    notify(sender: object, event: string): void;
}

class Button {
    constructor(private mediator: Mediator) {}

    click(): void {
        console.log('Button clicked');
        this.mediator.notify(this, 'click');
    }

    disable(): void {
        console.log('Button disabled');
        // 实际的禁用逻辑
    }
}

class TextBox {
    constructor(private mediator: Mediator) {}

    textChanged(): void {
        console.log('TextBox text changed');
        this.mediator.notify(this, 'textChanged');
    }

    setText(text: string): void {
        console.log(`TextBox text set to: ${text}`);
        // 实际的设置文本逻辑
    }
}

class List {
    constructor(private mediator: Mediator) {}

    selectionChanged(): void {
        console.log('List selection changed');
        this.mediator.notify(this, 'selectionChanged');
    }

    getSelectedValue(): string {
        // 实际获取选中值的逻辑
        return 'Selected Value';
    }
}

class ConcreteMediator implements Mediator {
    private button: Button;
    private textBox: TextBox;
    private list: List;

    constructor() {
        this.button = new Button(this);
        this.textBox = new TextBox(this);
        this.list = new List(this);
    }

    notify(sender: object, event: string): void {
        if (event === 'click') {
            // 处理按钮点击事件
        } else if (event === 'textChanged') {
            // 当文本框文本更改时,可能的逻辑
            this.list.selectionChanged(); // 例如更新列表
        } else if (event === 'selectionChanged') {
            // 当列表选择更改时,可能的逻辑
            this.textBox.setText(this.list.getSelectedValue()); // 例如更新文本框
        }
    }
}

const mediator = new ConcreteMediator();
// 使用mediator来协调按钮、文本框和列表的交互

// 模拟用户交互
mediator.notify(mediator, 'textChanged');
mediator.notify(mediator, 'selectionChanged');

系统组件间通信

中介者模式可以有效简化复杂系统中组件间的直接交互,多个组件(如服务、管理器、数据库)之间的通信可以通过中介者来协调,以降低系统各部分之间的耦合度。

// npm run code src/code/design-pattern/mediator/communication-between-system-components.ts

export {};

interface Mediator {
    notify(sender: object, event: string): void;
}

class Service {
    constructor(private mediator: Mediator) {}

    performAction(): void {
        console.log('Service performed an action');
        this.mediator.notify(this, 'ServiceAction');
    }
}

class Manager {
    constructor(private mediator: Mediator) {}

    handleEvent(): void {
        console.log('Manager handled an event');
        this.mediator.notify(this, 'ManagerEvent');
    }
}

class Database {
    constructor(private mediator: Mediator) {}

    dataChanged(): void {
        console.log('Database data changed');
        this.mediator.notify(this, 'DatabaseChange');
    }
}

class SystemMediator implements Mediator {
    private service: Service;
    private manager: Manager;
    private database: Database;

    constructor() {
        this.service = new Service(this);
        this.manager = new Manager(this);
        this.database = new Database(this);
    }

    notify(sender: object, event: string): void {
        if (event === 'ServiceAction') {
            console.log('Mediator reacts on ServiceAction and triggers following operations:');
            this.manager.handleEvent();
        } else if (event === 'ManagerEvent') {
            console.log('Mediator reacts on ManagerEvent and triggers following operations:');
            this.database.dataChanged();
        } else if (event === 'DatabaseChange') {
            console.log('Mediator reacts on DatabaseChange and can trigger additional operations');
            // 这里可以添加更多对数据库更改的响应逻辑
        }
    }
}

const mediator = new SystemMediator();
// 使用mediator来协调服务、管理器和数据库的交互

// 模拟一些操作
mediator.notify(mediator, 'ServiceAction');

飞机航班控制

中介者模式可以用来协调多架飞机的路径和起降,每架飞机通过中介者来请求降落或通报位置,确保它们保持安全距离。

// npm run code src/code/design-pattern/mediator/aircraft-flight-control.ts

export {};

interface AirTrafficControlMediator {
    registerFlight(flight: Flight): void;
    requestLanding(flight: Flight): void;
    notifyAboutFlightPosition(flight: Flight, position: Position): void;
}

class Flight {
    constructor(private mediator: AirTrafficControlMediator, public flightNumber: string) {}

    requestLanding(): void {
        console.log(`${this.flightNumber} requesting landing`);
        this.mediator.requestLanding(this);
    }

    changePosition(newPosition: Position): void {
        console.log(`${this.flightNumber} changing position to ${JSON.stringify(newPosition)}`);
        this.mediator.notifyAboutFlightPosition(this, newPosition);
    }

    // 其他飞机相关的方法
}

interface Position {
    x: number;
    y: number;
    altitude: number;
}

class AirTrafficControl implements AirTrafficControlMediator {
    private flights: Flight[] = [];

    registerFlight(flight: Flight): void {
        this.flights.push(flight);
        console.log(`Flight ${flight.flightNumber} registered with air traffic control`);
    }

    requestLanding(flight: Flight): void {
        // 实现起降请求的逻辑,确保安全距离等
        console.log(`Flight ${flight.flightNumber} cleared to land`);
    }

    notifyAboutFlightPosition(flight: Flight, position: Position): void {
        // 实现对飞机位置的响应逻辑,比如调整其他飞机的飞行路径以保持安全距离
        console.log(`Received position update from Flight ${flight.flightNumber}: ${JSON.stringify(position)}`);
    }
}

const atcMediator = new AirTrafficControl();

const flight1 = new Flight(atcMediator, 'FL123');
const flight2 = new Flight(atcMediator, 'FL456');

atcMediator.registerFlight(flight1);
atcMediator.registerFlight(flight2);

flight1.changePosition({ x: 100, y: 200, altitude: 30000 });
flight2.changePosition({ x: 150, y: 250, altitude: 32000 });

flight1.requestLanding();
flight2.requestLanding();

智能家居系统

中介者模式应用于智能家居系统,可以有效地协调各种智能设备之间的交互。这样,各设备不需要直接相互通信,而是使用中介者进行交互,使得系统整体更加模块化和易于管理。

// npm run code src/code/design-pattern/mediator/smart-home-system.ts

export {};

interface SmartHomeMediator {
    notify(event: string): void;
}

abstract class SmartDevice {
    constructor(protected mediator: SmartHomeMediator) {}

    abstract triggerEvent(event: string): void;
}

class Lights extends SmartDevice {
    triggerEvent(event: string): void {
        console.log(`Lights received event: ${event}`);
        this.mediator.notify(event);
    }

    turnOn(): void {
        console.log('Lights turned on');
    }

    turnOff(): void {
        console.log('Lights turned off');
    }
}

class AirConditioner extends SmartDevice {
    triggerEvent(event: string): void {
        console.log(`AirConditioner received event: ${event}`);
        this.mediator.notify(event);
    }

    setTemperature(temperature: number): void {
        console.log(`AirConditioner temperature set to ${temperature} degrees`);
    }
}

class SecuritySystem extends SmartDevice {
    triggerEvent(event: string): void {
        console.log(`SecuritySystem received event: ${event}`);
        this.mediator.notify(event);
    }

    activate(): void {
        console.log('Security system activated');
    }

    deactivate(): void {
        console.log('Security system deactivated');
    }
}

class SmartHome implements SmartHomeMediator {
    private lights: Lights = new Lights(this);
    private airConditioner: AirConditioner = new AirConditioner(this);
    private securitySystem: SecuritySystem = new SecuritySystem(this);

    notify(event: string): void {
        console.log(`Mediator notified of event: ${event}`);
        switch (event) {
            case 'ArrivedHome':
                this.lights.turnOn();
                this.airConditioner.setTemperature(22);
                this.securitySystem.deactivate();
                break;
            case 'LeftHome':
                this.lights.turnOff();
                this.securitySystem.activate();
                break;
            // 可以添加更多事件类型和逻辑
        }
    }

    // 方法来模拟事件触发
    simulateArrival(): void {
        this.lights.triggerEvent('ArrivedHome');
    }

    simulateDeparture(): void {
        this.securitySystem.triggerEvent('LeftHome');
    }
}

const smartHome = new SmartHome();

// 模拟家庭成员到家的情况
smartHome.simulateArrival();

// 模拟家庭成员离家的情况
smartHome.simulateDeparture();

上次编辑于: