Javascript-使用类(ES6)更改大量if语句
我现在在代码中使用了很多if语句, 所以我想通过使用类(ES6)进行更改 然而,我不太擅长Javascript。。。所以请帮帮我 先前代码:Javascript-使用类(ES6)更改大量if语句,javascript,node.js,oop,if-statement,design-patterns,Javascript,Node.js,Oop,If Statement,Design Patterns,我现在在代码中使用了很多if语句, 所以我想通过使用类(ES6)进行更改 然而,我不太擅长Javascript。。。所以请帮帮我 先前代码: //example code function first(){ console.log('first scenario called'); } function second(){ console.log('second scenario called'); } function third(){ console.log('third s
//example code
function first(){
console.log('first scenario called');
}
function second(){
console.log('second scenario called');
}
function third(){
console.log('third scenario called');
}
state = 1;
if(state === 1){
first();
}else if(state === 2){
second();
}else if(state === 3){
third();
}
//first scenario called
更改代码:
class Strategy {
constructor(state) {
this.state = state;
if(this.state === 1){
return first();
}else if (val === 2){
return second();
}else if (val === 3){
return third();
}
}
}
function first(){
console.log('first scenario called');
}
function second(){
console.log('second scenario called');
}
function third(){
console.log('third scenario called');
}
let firstClass = new Strategy(1);
//first scenario called
这是我的示例代码
事实上,我有将近50多个if语句。
这是改变很多if语句的正确方法吗 不要将状态用作整数并在if或switch语句中使用它。在自己的课堂上定义策略。这样,您就可以随时进行扩展,而不必修改一个将发展成为庞然大物的类 为什么要使用单独的类来实现额外的功能呢?您可能会想,什么时候只需要执行一两行呢? 现在你可能有一两行,但将来你可能需要在这里加一行,在那里加一行,在这里添加一个for循环,在这里和那里添加一些if语句,您将需要一些变量来记录一个状态,而您的20行程序最终将成为一个200-2000行的庞然大物,其中包含大量ifs和else,并且可能由于类似命名变量的输入错误而导致一些冲突状态。这些东西倾向于增长 通过关注点分离(google that),您可以在单个类中添加功能,而不必担心功能与其他任何功能重叠,并且您可以在任何时候通过一个管理策略的global Strater类添加其他内容。这些策略有自己的状态、一次性跑步者、间歇跑步者、xhr处理者等。。。不影响主要战略家的状态。它使你的代码清晰,你将能够看到什么代码导致什么。当您在6个月内拥有一个200行的庞然大物时,它会变得更加困难,因为一个东西属于一个状态,需要链接到正确的if语句,并且您可能会在另一个if语句中更新它 另外,通过使用单独的类,您可以自动测试它们所做的工作,从而更容易检查所有代码是否仍按预期工作
class Strategist {
constructor() {
this.strategies = {};
this.activeStrategy = -1;
this.strategy = null;
}
registerStrategy(strategy) {
this.strategies[strategy.getId()] = strategy;
}
setStrategy(id) {
if(this.activeStrategy != -1) {
if(this.strategies.hasOwnProperty(id)) {
this.activeStrategy = id;
}
else {
throw new Error("No such strategy was registered!");
}
}
else {
throw new Error("Another strategy is already active!");
}
}
run() {
this.strategies[ activeStrategy ].run();
}
public function stop() {
this.strategies[ this.activeStrategy ].stop();
this.strategies[ activeStrategy ].reset();
this.activeStrategy = -1;
}
}
然后定义策略。首先是一个全局父类
class Strategy {
constructor(external_id) {
this.id = external_id;
}
get getId() {
return this.id;
}
run(){};
stop(){};
reset(){};
}
然后是实际的策略。你在这里定义了需要发生什么
class StrategyFirst extends Strategy {
run() {
// do something
}
stop() {
// stop doing stuff
}
reset() {
// reset state
}
}
class StrategySecond extends Strategy {
run() {
// do something
}
stop() {
// stop doing stuff
}
reset() {
// reset state
}
}
然后将它们注册到最有策略的
strategist = new Strategist();
strategist.registerStrategy(new StrategyFirst("destroy all humans"));
strategist.registerStrategy(new StrategySecond("pluck a flower"));
然后,当事情发生了,你需要运行它,你可以要求你的战略家作出决定
strategist.setStrategy("pluck a flower");
下面的代码片段是一个小的实现示例,说明了这在现实世界中是如何工作的
class战略家{
构造函数(){
这个.strategies={};
this.activeStrategy=-1;
this.strategy=null;
}
注册策略(策略){
this.strategies[strategy.getId()]=策略;
}
设置策略(id){
if(this.activeStrategy==-1){
if(this.strategies.hasOwnProperty(id)){
this.activeStrategy=id;
}
否则{
抛出新错误(“未注册此类策略!”);
}
}
否则{
抛出新错误(“另一个策略已处于活动状态!”);
}
}
运行(){
this.strategies[this.activestrategie].run();
}
停止(){
this.strategies[this.activestrategie].stop();
this.strategies[this.activestrategie].reset();
this.activeStrategy=-1;
}
}
阶级策略{
构造函数(外部id){
this.id=外部_id;
}
getId(){
返回此.id;
}
运行(){};
停止(){};
重置(){};
}
类策略优先扩展策略{
运行(){
如果(!this.isRunning){
this.interval=window.setInterval(函数(){
窗户。警报(“嘘!又一个咬到了灰尘,嘟嘟嘟嘟”);
}, 3000);
this.isRunning=true;
}
}
停止(){
window.clearInterval(this.interval);
}
重置(){
this.interval=null;
this.isRunning=false;
}
}
类策略第二扩展策略{
运行(){
如果(!this.isRunning){
this.interval=window.setInterval(函数(){
警惕(“哦,看一朵漂亮的花*采摘*”);
}, 3000);
this.isRunning=true;
}
}
停止(){
window.clearInterval(this.interval);
}
重置(){
this.interval=null;
this.isRunning=false;
}
}
战略家=新战略家();
战略家。注册战略(新战略第一(“消灭所有人类”);
战略家。注册战略(新战略第二(“采花”);
document.getElementById(“执行”).addEventListener('click',function(){
var select=document.getElementById('fate');
策略师.setStrategy(select.options[select.selectedIndex].value);
战略家跑();
});
document.getElementById(“halt”).addEventListener('click',function(){
战略家。停止();
});代码>
消灭人类
毁花
执行命运
中断命运
又快又脏–不是首选方式
只需创建一个地图,其中的关键点为您提供了正确的功能:
this.strategies = {
1: this.first,
2: this.second,
3: this.third
}
然后搜索函数并执行它:
execute(value) {
this.strategies[value] == null
? console.log("this strategy does not exist")
: this.strategies[value]()
}
一个完整的工作示例
类策略{
构造函数(值){
这是一种策略={
1:这个,首先,,
2:这一秒,
3:这是第三次
}
这个。执行(值)
}
执行(值){
this.strategies[value]==null
?console.log(“此策略不存在”)
:this.strategies[值]()
}
第一(){
log(“调用的第一个场景”);
}
第二(){
log(“第二个场景被调用”);
}
第三(){
log(“第三个场景被调用”);
}
}
新策略(0);
新战略(1);
新战略(2);
新战略(3)代码>否。您可以使用包含函数的数组。使用