如何在不违反Typescript中的OCP的情况下创建工厂对象

问题描述 投票:-1回答:1

我只是了解一个工厂模式,并希望在Typescript中实现它。

我检查了许多网站,如this,并注意到所有的例子都违反了OCP,因为他们必须使用许多if语句来找到合适的子类构造函数。

我还发现了a similar question如何在Java中做到这一点。但我不知道它是否可以在打字稿中实现。

typescript types factory-pattern open-closed-principle
1个回答
0
投票

我不知道这是不是一个很好的做法,但你可以通过随机访问而不是顺序查找类来避免很多if语句。

你可以尝试这样的方式:

enum Behaviour {
  Friendly = 0,
  Agressive
}

export abstract class BaseCharacter{

  protected strength: number;

  public canFightWith(character: BaseCharacter): Boolean{
    return this.getBehaviour() !== character.getBehaviour();
  }

  public getStrength():number{
    return this.strength;
  }

  public abstract getBehaviour():Behaviour;

}

export class Vilain extends BaseCharacter{

  private reduction;

  public Vilain(strength:number, reduction:number){
    this.strength = strength;
    this.reduction = reduction;
  }

  public getStrength():number{
    return super.getStrength()*this.reduction;
  }

  public getBehaviour(): Behaviour {
    return Behaviour.Agressive;
  }
}

export class Hero extends BaseCharacter{

  public Hero(strength:number){
    this.strength = strength
  }

  public getBehaviour(): Behaviour {
    return Behaviour.Friendly;
  }
}

export class StaticFactory{

  // in this example Hero and Vilain will extend BaseCharacter

  static definitions = {
    'hero':Hero,
    'vilain':Vilain
  }

  static instanciateCharacter(subClass: string, ...args):BaseCharacter {
    if(subClass in StaticFactory.definitions)
      return new StaticFactory.definitions[subClass](...args);
  }

}

export class Battle{

  public constructor(private first: BaseCharacter, private second: BaseCharacter){
      if(!this.first.canFightWith(second))
        throw new Error("These 2 characters fight for the same cause !");
  }

  public getWinner():BaseCharacter{
    if (this.first.getStrength() === this.second.getStrength())
      return !(Math.trunc(Math.random()*2))?this.first:this.second;

    return this.first.getStrength() > this.second.getStrength()?this.first:this.second;

  }

}
© www.soinside.com 2019 - 2024. All rights reserved.