首页 > 解决方案 > 面向对象编程:另一种实现状态模式的方法?

问题描述

Object-oriented design在这个挑战中,我需要另一个解决方案的帮助 !技术负责人让我给出另一种解决方案。

这是挑战

军队由单位组成。一个单位可以是长枪手、弓箭手或骑士。长枪手可以变成弓箭手;弓箭手可以变骑士,骑士不能变。

这是我的解决方案

class Unit {}

class Pikeman extends Unit {
  transform() {
    return new Archer();
  }
}

class Archer extends Unit {
  transform() {
    return new Knight();
  }
}

class Knight extends Unit {
  transform() {
    throw new Error('a Knight can not be transformed');
  }
}

class Army {
  constructor() {
    this.units = [] // a collection of units
  }
  addUnit(unit) {
     units.push(unit);
  }
  
  transformUnits(units) {
     var unitsTransformed = units.map(u => u.transform())
  }
}

虽然技术负责人问我是否有另一种方法来实现该transform方法而不是返回一个新对象。

谁能帮我找到一个新的解决方案?

标签: javascriptoopstate-pattern

解决方案


这是我该怎么做。我希望它能解决你的问题。

const PIKEMAN = 0;
    const ARCHER = 1;
    const KNIGHT = 2;


    class Unit {
      // list of possible type of units, ordered by its hierarchy
      types = ["pikeman", "archer", "knight"];
      
      // current type of the unit
      current_type = 0;
      
      constructor(type = PIKEMAN){
        // by default, unit type is a pikeman 
        this.current_type = type;
      }
      
      transform(){
        // try to check, if it has a next hierarchy or not,
        let nextType = this.current_type + 1;
        
        // if its possible to transform it into the next unit type, then transform it
        if (this.types[nextType]) {
          this.current_type++;
          
          // return back the instance
          return this;
        }
        
        // get its current type on what unit this is.
        const currentType = this.types[ this.current_type ];
        
        // throw that i cannot be transformed anymore
        throw new Error("A "+currentType+" cannot be transformed")
      }
      
    }


    class Army {
      constructor(units = []) {
        this.units = units // a collection of units
      }
      addUnit(unit) {
         this.units.push(unit);
      }
      
      transformUnits() {
         return this.units.map(u => u.transform())
      }
    }


    let army = new Army([
      new Unit(PIKEMAN),  
      new Unit(ARCHER)
    ]);

    console.log(army.transformUnits());


推荐阅读