javascript - 面向对象编程:另一种实现状态模式的方法?
问题描述
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
方法而不是返回一个新对象。
谁能帮我找到一个新的解决方案?
解决方案
这是我该怎么做。我希望它能解决你的问题。
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());
推荐阅读
- amazon-web-services - 从 AWS 上托管的 Jupyter 笔记本访问非公共 RDS?
- loops - 从结构片段中删除具有重复字段值的结构
- python - 两个数组之间的字谜
- laravel - 如何从子过滤器循环返回true到集合laravel上的每个循环
- ruby - 如何使用 gem `memory_profiler` 编写单元测试?
- javascript - React Native - JSON对象的数组属性返回未定义,其他属性都返回一个值
- unity3d - Unity:导航网格代理不会留在角色内部
- plsql - PL/SQL:我得到表达式“我”不能用作赋值目标
- c# - 如何在 ASP.NET C# 具有 @ 的字符串 1 处输入字符串 2 值?
- c++ - Lua库没有链接