在R语言中使用设计模式

24
在编程中广泛使用设计模式,许多编程语言都有应用。一些例子是工厂单例设计模式。这些模式大多利用面向对象的方式在代码中创建抽象和封装,目的是使代码可重用且结构化。在R中也可以使用许多这些设计模式,可能需要使用proto库或标准R对象导向? 我的问题是:
  • 我可以使用哪些基本代码(S3、S4)/包(proto、R.oo)来复现例如Gamma等人所述的设计模式?
  • 是否有R中实现设计模式的示例,无论是在基本R中还是在包中?

1
R.oo包在R语言中提供了类似面向对象编程的功能(使用S3类)。它不支持完整的面向对象编程特性,因此也不支持完整的基于面向对象编程的设计模式。我还会看一下S4类http://www.stat.auckland.ac.nz/S-Workshop/Gentleman/S4Objects.pdf。 - Suraj
S4类看起来很有前途,尽管与Python等语言相比,构建对象的方式看起来有些笨拙。 - Paul Hiemstra
1
我使用引用类实现了《Head First设计模式》中勾勒出的几种设计模式。它们更接近于其他语言中的面向对象使用,而不像S4方法那样需要进行较少的翻译。 - jverzani
你能否在回答中发布你的工作链接?或者如果它还没有在线上,可以在回答中发布一些代码吗? - Paul Hiemstra
1
好的,我在这里放了一个单例模式的例子:https://gist.github.com/1953641 这实际上是一项正式的练习,对于R用户来说可能有些晦涩。虽然memoise包可以更轻松地完成这个任务,但我确实有一个使用案例。这个结构的基本思想来自《Head First》书籍。 - jverzani
很抱歉,但这个问题与R/oop问题[此处](https://dev59.com/Kmkw5IYBdhLWcg3w_Pbn)属于同一类别,它太广泛了,不适合SO的问答格式。 - Lasse V. Karlsen
1个回答

阿里云服务器只需要99元/年,新老用户同享,点击查看详情
5

设计模式的一些示例:

  • The system.time() function seems to behave much like a decorator pattern. However, almost exclusively decorators are mentioned in the context of object oriented programming. But still, it has the feel of a decorator, it extends (or decorates) an existing piece of code (in OOP always an object) with additional functionality without any need to change the piece of code. Here system.time() is shown in action:

    system.time(bla <- Sys.sleep(1000))
    
  • @jverzani posted an example of singleton pattern on github.

  • An example of a Strategy Design Pattern is the apply family of functions. The functionality of looping over the given object is generic, the function that is applied (the strategy) is chosen when the user supplies the function.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,