首页 > 其他分享 >typescript: Mediator pattern

typescript: Mediator pattern

时间:2023-10-12 13:34:04浏览次数:35  
标签:typescript console log mediator pattern Mediator Component notify

 

/**
 * 
 * Mediator pattern 中介者是一种行为设计模式, 让程序组件通过特殊的中介者对象进行间接沟通, 达到减少组件之间依赖关系的目的。
 * file: Mediatorts.ts
 * The Mediator interface declares a method used by components to notify the
 * mediator about various events. The Mediator may react to these events and
 * pass the execution to other components.
 */
interface Mediator {


    notify(sender: object, event: string): void; //void
}

/**
 * Concrete Mediators implement cooperative behavior by coordinating several
 * components.
 */
class ConcreteMediator implements Mediator {

    private component1: Component1;

    private component2: Component2;

    

    constructor(c1: Component1, c2: Component2) {

        this.component1 = c1;
        this.component1.setMediator(this);
        this.component2 = c2;
        this.component2.setMediator(this);
    }

    public notify(sender: object, event: string):string  { //void
        let getstr="";
        if (event === 'A') {
            console.log('Mediator reacts on A and triggers following operations:');
            this.component2.doC();
            getstr="Mediator reacts on A and triggers following operations:";
            getstr=getstr+this.component2.doC();
        }

        if (event === 'D') {
            console.log('Mediator reacts on D and triggers following operations:');
            this.component1.doB();
            this.component2.doC();
            getstr="Mediator reacts on D and triggers following operations:";
            getstr=getstr+this.component1.doB()+","+this.component2.doC();
        }

        return getstr;

    }
}

/**
 * The Base Component provides the basic functionality of storing a mediator's
 * instance inside component objects.
 */
class BaseComponent {

    protected mediator: Mediator;

    constructor(mediator?: Mediator) {
        this.mediator = mediator!;
    }

    public setMediator(mediator: Mediator): void {
        this.mediator = mediator;
    }
}

/**
 * Concrete Components implement various functionality. They don't depend on
 * other components. They also don't depend on any concrete mediator classes.
 */
class Component1 extends BaseComponent {

    /**
     * 
     * @returns 
     */
    public doA(): string { //void
        console.log('Component 1 does A.');
        this.mediator.notify(this, 'A');

        return "Component 1 does A."
    }
    /**
     * 
     * @returns 
     */
    public doB(): string { //void
        console.log('Component 1 does B.');
        this.mediator.notify(this, 'B');

        return "Component 1 does B.";
    }
}

/**
 * 
 */
class Component2 extends BaseComponent {

    /**
     * 
     * @returns 
     */
    public doC(): string {
        console.log('Component 2 does C.');
        this.mediator.notify(this, 'C');
        return "Component 2 does C.";
    }
    /**
     * 
     * @returns 
     */
    public doD(): string {
        console.log('Component 2 does D.');
        this.mediator.notify(this, 'D');
        return "Component 2 does D.";
    }
}

let pubMediator1="";
let pubMediator2="";
let pubMediator3="Geovin Du";
let pubMediator4="geovindu";

/**
 * The client code.
 */
const c1 = new Component1();

const c2 = new Component2();

const mediator = new ConcreteMediator(c1, c2);

console.log('Client triggers operation A.');
pubMediator1=c1.doA();

console.log('');
console.log('Client triggers operation D.');
pubMediator2=c2.doD();

pubMediator3=mediator.notify(c1,"A");//B

pubMediator4=mediator.notify(c2,"D");//C


let messageMediator: string = 'Hello World,This is a typescript!,涂聚文 Geovin Du.Web';
document.body.innerHTML = messageMediator+",<br/>one="+pubMediator1+",<br/>two="+pubMediator2+",<br/>three="+pubMediator3+",<br/>four="+pubMediator4+",<br/>TypeScript Command Pattern 命令模式";

  

调用:

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <head><title>TypeScript Hello Mediator pattern 中介者模式</title>
      <meta name="Description" content="geovindu,涂聚文,Geovin Du"/>
<meta name="Keywords" content="geovindu,涂聚文,Geovin Du"/>
<meta name="author" content="geovindu,涂聚文,Geovin Du"/> 
    </head>
    <body>
        <script src="dist/Mediatorts.js"></script>
    </body>
</html>

  

 

输出:

 

标签:typescript,console,log,mediator,pattern,Mediator,Component,notify
From: https://www.cnblogs.com/geovindu/p/17759269.html

相关文章

  • typesciprt: Command Pattern
     /****CommandPattern命令是一种行为设计模式,它可将请求或简单操作转换为一个对象。*file:Commandts.ts*TheCommandinterfacedeclaresamethodforexecutingacommand.**/interfaceCommand{execute():string;//void}/***Somecomm......
  • 【愚公系列】2023年10月 二十三种设计模式(十)-外观模式(Facade Pattern)
    ......
  • typescript: Template Method pattern
     /***TemplateMethodpattern模版方法是一种行为设计模式,它在基类中定义了一个算法的框架,允许子类在不修改结构的情况下重写算法的特定步骤。*file:Templatets.ts*TheAbstractClassdefinesatemplatemethodthatcontainsaskeletonofsome*algorithm,......
  • typescript: State Pattern
     /***StatePattern状态是一种行为设计模式,让你能在一个对象的内部状态变化时改变其行为。*TheContextdefinestheinterfaceofinteresttoclients.Italsomaintainsa*referencetoaninstanceofaStatesubclass,whichrepresentsthecurrent*stat......
  • typescript: Iterator Pattern
     /***IteratorPattern迭代器是一种行为设计模式,让你能在不暴露复杂数据结构内部细节的情况下遍历其中所有的元素*file:Iteratorts.tsnpminstall-gbabel-cli*Intent:Letsyoutraverseelementsofacollectionwithoutexposingits*underlyingrepres......
  • typescript: Memento Pattern
     /***MementoPattern备忘录是一种行为设计模式,允许生成对象状态的快照并在以后将其还原。*TheOriginatorholdssomeimportantstatethatmaychangeovertime.Italso*definesamethodforsavingthestateinsideamementoandanothermethodfor*re......
  • typescript: Chain of Responsibility Pattern
     /***ChainofResponsibilityPattern责任链是一种行为设计模式,允许你将请求沿着处理者链进行发送,直至其中一个处理者对其进行处理。*file:Chaints.ts*TheHandlerinterfacedeclaresamethodforbuildingthechainofhandlers.*Italsodeclaresameth......
  • 【愚公系列】2023年10月 二十三种设计模式(九)-装饰者模式(Decorator Pattern)
    ......
  • [Typescript] Type and Interface for performance
    Let'ssayyou'recreatingacomponentthathasallthepropsof input butneedstoadda label prop.You'llneedtoextendfromthe ComponentProps typehelperimport{ComponentProps}from"react";exporttypeInputProps=Co......
  • typescript: Flyweight Pattern
     /***FlyweightPattern享元是一种结构型设计模式,它允许你在消耗少量内存的情况下支持大量对象。*https://refactoringguru.cn/design-patterns/flyweight/typescript/example#lang-features*TheFlyweightstoresacommonportionofthestate(alsocalledintr......