Objective-C类别==访问者模式? [英] Objective-C categories == visitor pattern?

查看:91
本文介绍了Objective-C类别==访问者模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您会说Objective-C类别是访客设计模式的实现吗?

Would you say that Objective-C categories are an implementation of the visitor design pattern?

推荐答案

不,Objective-C类别不是访客模式的实现。在设计模式世界中,类别实际上并没有完全匹配,因为在大多数语言中,无法将方法注入现有类而不使用子类的技术。我想说它更接近装饰器模式,但是该模式通常是通过合成实现的,即通过包装您要增强的对象的实例。

No, Objective-C categories are not an implementation of the visitor pattern. Categories don't really have an exact match in the design pattern world, since the technique of injecting methods into existing classes without subclasses isn't possible in most languages. I'd say it's closer to the decorator pattern, but that pattern is usually implemented with composition, i.e. by wrapping an instance of the object you want to "enhance".

访问者模式对于封装可应用于各种对象,结构,例如,如果要为对象图创建HTML输出,则可以(A)在每个对象上编写一个 htmlString 方法,并为每个对象调用它,或(B)使用访问者模式并创建一个具体的访问者,该访问者知道如何为其访问的每个节点生成HTML输出。

The visitor pattern is useful for encapsulating algorithm logic that may be applied to a variety of objects, structs, etc. For example, if you want to create HTML output for a graph of objects, you could (A) write a htmlString method on each object and call it for each object, or (B) use the visitor pattern and create a concrete visitor that knows how to produce HTML output for each node it visits.

前一种方法较为通用,任务T的逻辑分散在X,Y和Z类中的小块中。后一种方法将所有相关代码放在单个访问者对象中,这倾向于简化维护并防止我忘记了一个类...问题。但是,在简单情况下,访问者模式可以说是费力的-当您具有多个不同的并行功能并且希望从执行该功能的类中抽象逻辑时,访问者模式才真正有回报。例如,您可以实现产生PDF或RTF输出等的其他访问者。每个访问者都可以执行递归并按必要的顺序调用其自己的访问方法,并且单独的访问者可以使用完全不同的顺序。

The former approach is more generic, and the logic for task T is scattered in small chunks across classes X, Y and Z. The latter approach places all the related code in a single visitor object, which tends to simplify maintenance and prevent the "I forgot that one class..." problem. However, the visitor pattern is arguably somewhat heavy-handed for simple situations — where it really pays off is when you have several different parallel functionalities and wish to abstract the logic from the classes on which the functionality is being performed. For example, you might implement other visitors which produce PDF or RTF output, etc. Each visitor can take care of recursion and calling its own visit methods in the order necessary, and separate visitors can use a completely distinct order.

应注意,在许多语言中,访问者模式都使用方法重载(相同的名称,不同的签名/参数)。由于Objective-C不允许方法重载,因此您必须使用不同的方法名称,但这实际上可以避免由于不知道调用哪个重载而导致的错误。

It should be noted that in many languages, the visitor pattern uses method overloading (same name, different signature/arguments). Since Objective-C doesn't allow method overloading, you must use distinct method names, but this can actually help avoid bugs caused by not knowing which overloading is being called.

这篇关于Objective-C类别==访问者模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆