2017-05-26 50 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);