如何在打字稿中创建装饰模式?

时间:2016-11-04 18:18:50

标签: javascript typescript proxy decorator

我正在尝试从一组类创建对象而不必定义每个集合...本质上我正在尝试创建装饰器模式。在打字稿中,由于编译限制,这似乎几乎不可能。

我尝试过使用Proxies。没有骰子。

这是我想要完成的用法(缺少一些代码以允许我正在尝试做的事情 - 这就是我想要解决的问题。)

class Person {

    public name:string;
    public age:number;

    public identify(){
        console.log(`${this.name} age ${this.age}`);
    }


}

class Child {

    public Mother:Person;
    public Father:Person;

    public logParents(){
        console.log("Parents:");
        this.Mother.identify();
        this.Father.identify();
    }

}

class Student {

    public school:string;

    public logSchool(){
        console.log(this.school);
    }

}

let Dad = new Person();
Dad.name = "Brad";
Dad.age = 32;

let Mom = new Person();
Mom = new Student(Mom);
Mom.name = "Janet";
Mom.age = 34;
Mom.school = "College of Night School Moms";

let Johnny = new Person();
Johnny = new Child(Johnny);
Johnny = new Student(Johnny);
Johnny.name = "Johnny";
Johnny.age = 12;
Johnny.Mother = Mom;
Johnny,Father = Dad;
Johnny.school = "School for kids who can't read good";

1 个答案:

答案 0 :(得分:0)

使用java example here作为基础,我稍微更改了一下以适合您的代码:

interface Person {
    name: string;
    age: number;
    identify(): void;
}

class SimplePerson implements Person {
    public name: string;
    public age: number;

    public identify(){
        console.log(`${this.name} age ${this.age}`);
    }
}

abstract class PersonDecorator implements Person {
    protected decoratedPerson: Person;

    public constructor(person: Person) {
        this.decoratedPerson = person;
    }

    public get name() {
        return this.decoratedPerson.name;
    }

    public get age() {
        return this.decoratedPerson.age;
    }

    identify(): void {
        return this.decoratedPerson.identify();
    }
}

class Child extends PersonDecorator {
    public Mother: Person;
    public Father: Person;

    public logParents(){
        console.log("Parents:");
        this.Mother.identify();
        this.Father.identify();
    }
}

class Student extends PersonDecorator {
    public school:string;

    public logSchool(){
        console.log(this.school);
    }
}

let Dad = new SimplePerson();
Dad.name = "Brad";
Dad.age = 32;

let Mom = new SimplePerson();
Mom = new Student(Mom);
Mom.name = "Janet";
Mom.age = 34;
(Mom as Student).school = "College of Night School Moms";

let Johnny = new SimplePerson();
Johnny = new Child(Johnny);
Johnny = new Student(Johnny);
Johnny.name = "Johnny";
Johnny.age = 12;
(Johnny as Child).Mother = Mom;
(Johnny as Child).Father = Dad;
(Johnny as Student).school = "School for kids who can't read good";

code in playground