JavaScript Design Patterns (Strategy Pattern)

Defined policy model are: the definition of a family of algorithms, encapsulate each one them, and make them interchangeable. Part of the same part of the separating and change is the theme of each design pattern, strategy pattern is no exception, the purpose of the policy is to achieve mode algorithm uses an algorithm separated.

First, the initial strategy pattern:

var calculateBonus = function( performanceLevel, salary ){
  if ( performanceLevel === 'S' ){ 
    return salary * 4;
  }
  if ( performanceLevel === 'A' ){ 
    return salary * 3;
  }
  if ( performanceLevel === 'B' ){ 
    return salary * 2;
  } 
};
calculateBonus( 'B', 20000 ); // 输出:40000 calculateBonus( 'S', 6000 ); // 输出:24000

 The combination codes or improved function package

var performanceS = function( salary ){ 
  return salary * 4;
};
var performanceA = function( salary ){ 
  return salary * 3;
};
var performanceB = function( salary ){ 
  return salary * 2;
};
var calculateBonus = function( performanceLevel, salary ){
  if ( performanceLevel === 'S' ){ 
    return performanceS( salary );
  }
  if ( performanceLevel === 'A' ){ 
    return performanceA( salary );
  }
  if ( performanceLevel === 'B' ){ 
    return performanceB( salary );
  }
}

calculateBonus( 'A' , 10000 ); // 输出:30000

However, this improvement is very limited, calculateBonus function it is possible to grow in size, and the lack of flexibility when the system changes.

Second, the strategy pattern:

 

Guess you like

Origin www.cnblogs.com/angelatian/p/11771976.html