此代码是对status(OrderStatus.keys)字符串进行比较的一种简单尝试。状态更新只能向前移动。因此,如果等待批准在批准之后到来,则可以拒绝。
构造函数由于对象创建的锁定而引发错误。
如何解决?
export class OrderStatus{
private static keys = ['draft', 'waiting-approval', 'approved', ..];
private static keyMaps = {};
static DRAFT = new OrderStatus(OrderStatus.keys[0], 1); // execution starts here
static WAITINGAPPROVAL = new OrderStatus(OrderStatus.keys[1], 2);
static APPROVED = new OrderStatus(OrderStatus.keys[2], 3);
private constructor(private _key: string, private _index: number) {
this.initialize(); // error on run
}
private initialize(){
OrderStatus.keyMaps[OrderStatus.keys[0]] = OrderStatus.DRAFT; // draft object not yet ready because of above static block
OrderStatus.keyMaps[OrderStatus.keys[1]] = OrderStatus.WAITINGAPPROVAL;
OrderStatus.keyMaps[OrderStatus.keys[2]] = OrderStatus.APPROVED;
}
static resolve(key : string) : OrderStatus {
return OrderStatus.keyMaps[key];
}
get index() {
return this._index;
}
toString() {
return this._key;
}
compare(value1: OrderStatus){
return value1.index < this.index ? -1 : (value1.index > this.index ? 1 : 0);
}