2 回答

TA貢獻1815條經驗 獲得超6個贊
一個簡單的解決方案是根本不重寫respondToThreat,而是調用應由子類實現的方法/掛鉤。
class NuclearStrategy {
constructor(props) {
this.eventOrigin = props.eventOrigin;
}
appeaseAllPopulation() {
console.log('Broadcasting ');
}
respondToThreat({ eventIsJustTest }) {
console.log(`? Appeasing the population`);
if (eventIsJustTest) return;
this.respondToNonTestThreat();
}
respondToNonTestThreat() {} // default implementation do nothing
}
class Action extends NuclearStrategy {
respondToNonTestThreat() {
console.log(`? Playing alert siren`);
console.log(`? Launched ICBM nuke to enemy`);
}
}
const action = new Action({ eventOrigin: 'East Qorea' });
console.log("test threat:");
action.respondToThreat({ eventIsJustTest: true });
console.log("non-test threat:");
action.respondToThreat({});

TA貢獻1802條經驗 獲得超10個贊
如果您想防止程序員重寫重要方法,您可以只傳遞要執行的邏輯,而不是子類化。在這種情況下,調用邏輯的類應該記錄在什么情況下執行什么邏輯。傳遞的參數是什么以及期望的返回值應該是什么。
上面的內容可以通過很多不同的方式來完成,下面是一個例子:
class Hooks {
constructor(hooks, context) {
this.hooks = hooks;
this.context = context;
}
find(...path) {
let cursor = this.hooks;
for (const key of path) {
if (!cursor[key]) return this.noop;
cursor = cursor[key];
}
return cursor.bind(this.context);
}
noop() {}
}
class NuclearStrategy {
static withPresetHooks(hooks) {
return (props) => new this({ ...props, hooks });
}
constructor(props) {
this.eventOrigin = props.eventOrigin;
this.hooks = new Hooks(props.hooks || {}, this);
}
appeaseAllPopulation() {
console.log('Broadcasting ');
}
respondToThreat({ eventIsJustTest }) {
console.log(`? Appeasing the population`);
this.hooks.find("respondToThreat", "eventIsJustTest", !!eventIsJustTest)();
}
}
const createAction = NuclearStrategy.withPresetHooks({
respondToThreat: {
eventIsJustTest: {
true: function () {
console.log(`? Testing alert siren`);
},
false: function () {
console.log(`? Playing alert siren`);
console.log(`? Launched ICBM nuke to enemy`);
},
},
},
});
const action = createAction({ eventOrigin: 'East Qorea' });
console.log("test threat:");
action.respondToThreat({ eventIsJustTest: true });
console.log("non-test threat:");
action.respondToThreat({});
添加回答
舉報