2016-11-04 50 views
0

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

我试过使用代理。没有骰子。

以下是我正在尝试完成的用法(某些代码缺失以允许我正在尝试执行的操作 - 这是我正在尝试解决的问题)。

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"; 

回答

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

+0

(约翰尼如儿童).logParents()不会在这里工作。 – Bradley

+0

没错。我错过了,在java例子中他们有私有方法而不是公共方法,这就是为什么它不是问题。但是这个问题存在于java中,可能还有其他OO语言。基本上你正在寻找与mixin的装饰模式。在typescript/javascript中,这可能比使用或不使用代理服务器的可能性要大,但我怀疑它可能有点矫枉过正,至少在大多数情况下是这样。你的场景是什么?你的代码只是你问题的一个例子,还是你真正的模型? –

+0

这只是一个简单的例子。真正的场景还有更多...基本上是一系列“扩展”的基础对象,可以在任意数量的组合中进行混合和匹配。 – Bradley