策略模式和访客模式有什么区别? [英] What is the difference between Strategy pattern and Visitor Pattern?
问题描述
我很难理解这两种设计模式.
I have trouble understanding these two design patterns.
能否请您给我提供上下文信息或示例,以便我有一个清晰的主意并能够绘制出两者之间的区别.
Can you please give me contextual information or an example so I can get a clear idea and be able to map the difference between the two of them.
谢谢.
推荐答案
策略模式就像是一种 1:很多关系.当存在一种类型的对象并且我想对其应用多个操作时,我将使用策略模式.例如,如果我有一个封装视频剪辑的Video类,则可能要以不同的方式压缩它.因此,我创建了一堆策略类:
The strategy pattern is like a 1:many relationship. When there is one type of object and I want to apply multiple operations to it, I use the strategy pattern. For example, if I have a Video class that encapsulates a video clip, I might want to compress it in different ways. So I create a bunch of strategy classes:
MpegCompression
AviCompression
QuickTimeCompression
以此类推.
我认为访客模式是 many:many 关系.假设我的应用程序增长到不仅包括视频,还包括音频剪辑.如果我坚持使用策略模式,则必须重复压缩类-一种用于视频,另一种用于音频:
I think of the visitor pattern as a many:many relationship. Let's say my application grows to to include not just video, but audio clips as well. If I stick with the strategy pattern, I have to duplicate my compression classes-- one for video and one for audio:
MpegVideoCompression
MpegAudioCompression
以此类推...
如果切换到访问者模式,则不必重复策略类.我通过添加方法来实现我的目标:
If I switch to the visitor pattern, I do not have to duplicate the strategy classes. I achieve my goal by adding methods:
MpegCompressionVisitor::compressVideo(Video object)
MpegCompressionVisitor::compressAudio(Audio object)
[更新:使用Java] 我在Java应用程序中使用了访问者模式.结果与上面描述的略有不同.这是此示例的Java版本.
[UPDATE: with Java] I used the visitor pattern in a Java app. It came out a little different than described above. Here is a Java version for this example.
// Visitor interface
interface Compressor {
// Visitor methods
void compress(Video object);
void compress (Audio object)
}
// Visitor implementation
class MpegCompressor implements Compressor {
public void compress(Video object) {
System.out.println("Mpeg video compression");
}
public void compress(Audio object) {
...
}
}
现在要访问的接口和类:
And now the interface and class to be visited:
interface Compressible {
void accept(Compressor compressor);
}
class Video implements Compressible {
// If the Compressor is an instance of MpegCompressionVisitor,
// the system prints "Mpeg video compression"
void accept(Compressor compressor) {
compressor.compress(this);
}
这篇关于策略模式和访客模式有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!