2016-11-04 76 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