在计算机编程中,策略模式(也称为策略模式)是一种行为软件设计模式,可以在运行时选择算法的行为。
策略模式...
(来源:维基百科)
就我而言,我希望能够将不同的哈希算法注入到服务中。C# 有多种源自HashAlgorithm 的哈希算法,例如:
考虑到这个层次结构,这看起来像策略模式,但如果我从未听说过策略模式,我可能会说这是多态性的经典示例。
在设计代码来解决我的特定问题时,我设计了一个基于策略模式的接口来注入不同的哈希算法:
public interface IHashStrategy
{
Hash ComputeHash(byte[] data);
}
Run Code Online (Sandbox Code Playgroud)
用法
public sealed class HashCreator
{
public Hash GetHash(IHashStrategy strategy, byte[] data)
{
return strategy.ComputeHash(data);
}
}
Run Code Online (Sandbox Code Playgroud)
回到我之前的例子,我同样可以完全摆脱界面并只使用HashAlgorithm
:
public sealed class HashCreator
{
public Hash GetHash(HashAlgorithm algorithm, byte[] data)
{
return new Hash(algorithm.ComputeHash(data));
}
}
Run Code Online (Sandbox Code Playgroud)
问题 1:策略模式与多态性有什么不同,还是因为多态性才存在策略模式?
问题 2:这里认为哪种做法更好?将我需要的功能抽象为接口 ( IHashStrategy
) 还是使用基本类型 ( HashAlgorithm
)?
假设我有以下基类,Queen和Knight作为它的衍生物.WeaponBehaviour是一个界面.根据具体的GameCharacter类型,我无法弄清楚如何使用Guice注入武器.
public abstract class GameCharacter {
@Inject
protected WeaponBehaviour weapon;
public GameCharacter() {
}
public void fight() {
weapon.useWeapon();
}
public void setWeapon(WeaponBehaviour weapon) {
this.weapon = weapon;
}
}
Run Code Online (Sandbox Code Playgroud) 我有一个Factory类,它根据给定文件的扩展名返回一个编写器策略:
public static function getWriterForFile($file)
{
// create file info object
$fileInfo = new \SplFileInfo($file);
// check that an extension is present
if ('' === $extension = $fileInfo->getExtension()) {
throw new \RuntimeException(
'No extension found in target file: ' . $file
);
}
// build a class name using the file extension
$className = 'MyNamespace\Writer\Strategy\\'
. ucfirst(strtolower($extension))
. 'Writer';
// attempt to get an instance of the class
if (!in_array($className, get_declared_classes())) {
throw new \RuntimeException(
'No writer could be found …
Run Code Online (Sandbox Code Playgroud) 我正在编写一个正则表达式解析器,其中一个循环切换反模式似乎是唯一的方法.请忽略实际的解析规则,因为这个解析逻辑只是为内部应用程序定制的,并且不同于常用.
public static boolean match(String regex, String str) {
int i = 0;
int j = 0;
while ((i < regex.length() && j < str.length())) {
switch(regex.charAt(i)) {
case '.' : i++; j++; break;
case '*' : // do something ; break
default : if (regex.charAt(i) != str.charAt(j)) { return false; } else {i++; j++};
}
}
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下如何防止环路开关?是否有任何设计模式用于此目的?
java loops design-patterns strategy-pattern switch-statement