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({});
添加回答
举报