是否有设计模式或策略来处理以下情况:
通过各种不同方法转换字符串的3种不同策略:解码,解密,删除特定位置的字符串部分,转换为数组等。
每个策略使用可能的转换的不同组合来实现其在字符串上的最终结果。
我有一个类负责每个转换,例如:Decoder,Decrypter,Splicer等。我有3个具体的类,它需要将变换器注入到它的构造函数中。
此问题是否存在可接受的设计模式。我觉得有一种更优雅的方式来实现这一目标但却看不到它
答案 0 :(得分:1)
使用 Command 对象或命令模式称为责任链模式。
我可以写一些代码,但WikiPedia做得更好。 Chain-Of-Responsibility
你的想法是构建 Command 对象(Decoder,Decrypter等)并按照他们的责任顺序排列。
责任链来自他们的订购。
对于您的三种不同策略,您已经在描述该模式。他们最好的是策略模式。 Strategy Pattern
一些假的语言:
interface Action {
public void execute()
}
class Decoder extends Action {
public void execute() {
I'm decoding
}
}
class Decrypter extends Action {
public void execute() {
I'm decrypting
}
}
对于Decrypter或Decoder的每个不同实现,只需实现新版本的Decrypter或Decoder。与您的课程相关联的Action
实施将在调用execute()
那就是它。至少我认为这是你所描述的。