2017-05-26 51 views
-2

是否可以執行此答案中提供的等效項,但在Typescript中?在Typescript中擴展生成器

Subclassing a Java Builder class

這裏是我迄今爲止的基礎類:

export class ProfileBuilder { 
    name: string; 

    withName(value: string): ProfileBuilder { 
     this.name= value; 
     return this; 
    } 

    build(): Profile{ 
     return new Profile(this); 
    } 
} 

export class Profile { 
    private name: string; 

    constructor(builder: ProfileBuilder) { 
     this.name = builder.Name; 
    } 
} 

和擴展類:

export class CustomerBuilder extends ProfileBuilder { 
    email: string; 

    withEmail(value: string): ProfileBuilder { 
     this.email = value; 
     return this; 
    } 

    build(): Customer { 
     return new Customer(this); 
    } 
} 

export class Customer extends Profile { 
    private email: string; 

    constructor(builder: CustomerBuilder) { 
     super(builder); 
     this.email= builder.email; 
    } 
} 

像其他線程提到,我不會像能夠根據上下文的變化建立客戶:

let customer: Customer = new CustomerBuilder().withName('John') 
               .withEmail('[email protected]') 
               .build(); 

我目前正在嘗試使用泛型來解決這個問題,但是我在爲setter方法返回這個指針時遇到了麻煩(鍵入這個不能分配給類型T)。有任何想法嗎?

+2

請花一些時間來閱讀的https:/ /stackoverflow.com/help/how-to-ask指南。它會幫助你獲得答案。 :) – toskv

+1

是的,我正在編輯問題的過程中給我一個具體的例子,我到目前爲止。 – user2595996

回答

0

找到了解決方案!看着其他線程我mentionned在不同的答案後,我結束了創建一個抽象基類和建設者再延長我的每一個類/建設者對:

abstract class BaseProfileBuilder<T extends BaseProfile, B extends BaseProfileBuilder<T, B>> { 
    protected object: T; 
    protected thisPointer: B; 

    protected abstract createObject(): T; 

    protected abstract getThisPointer(): B; 

    constructor() { 
     this.object = this.createObject(); 
     this.thisPointer = this.getThisPointer(); 
    } 

    withName(value: string): B { 
     this.object.name = value; 
     return this.thisPointer; 
    } 

    build(): T { 
     return this.object; 
    } 
} 

abstract class BaseProfile { 
    name: string; 
} 

class ProfileBuilder extends BaseProfileBuilder<Profile, ProfileBuilder> { 
    createObject(): Profile { 
     return new Profile(); 
    } 

    getThisPointer(): ProfileBuilder { 
     return this; 
    } 
} 

class Profile extends BaseProfile { 
} 

class CustomerBuilder extends BaseProfileBuilder<Customer, CustomerBuilder> { 
    createObject(): Customer { 
     return new Customer(); 
    } 

    getThisPointer(): CustomerBuilder { 
     return this; 
    } 

    withEmail(value: string): CustomerBuilder { 
     this.object.email = value; 
     return this; 
    } 
} 

class Customer extends BaseProfile { 
    email: string; 
} 


let customer: Customer = new CustomerBuilder().withName('John') 
               .withEmail('[email protected]') 
               .build(); 

console.log(customer);