如何以纯功能方式实现观察者设计模式? [英] How to implement the Observer Design Pattern in a pure functional way?

查看:103
本文介绍了如何以纯功能方式实现观察者设计模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想使用OO编程语言实现事件总线。
我可以这样做(伪代码):

Let's say I want to implement an event bus using a OO programming language. I could do this (pseudocode):

class EventBus

    listeners = []

    public register(listener):
        listeners.add(listener)

    public unregister(listener):
        listeners.remove(listener)

    public fireEvent(event):
        for (listener in listeners):
            listener.on(event)

这实际上是观察者模式,但用于应用程序的事件驱动控制流程。

This is actually the the observer pattern, but used for event-driven control flow of an application.

使用函数式编程语言(比如lisp中的一种)实现这个模式?

How would you implement this pattern using a functional programming language (such as one of the lisp flavors)?

我问这个问题,因为如果没有使用对象,种状态来维护所有监听器的集合。更多的,因为侦听器集合随着时间的推移而变化,所以不可能创建一个纯的功能解决方案。

I ask this because if one doesn't use objects, one would still need some kind of state to maintain a collection of all the listeners. More over, since the listeners collection changes over time, it would not be possible to create a pure functional solution, right?

推荐答案

关于此的一些评论:

我不知道如何做,但有一些名为功能反应编程,它可用作许多功能语言的库。这实际上或多或少是观察者模式做的正确。

I am not sure how it is done, but there is something called "functional reactive programming" which is available as a library for many functional languages. This is actually more or less the observer pattern done right.

此外,观察者模式通常用于通知状态的变化,如在各种MVC实现中。但是在函数式语言中没有直接的方式来做状态变化,除非你使用一些技巧,如monad来模拟状态。但是如果你使用monad模拟状态变化,你也可以在monad中添加观察者机制。

Also the observer pattern is usually used for notifying changes in state, as in the various MVC implementations. However in a functional language there is no direct way to do state-changes, unless you use some tricks such as monads to simulate the state. However if you simulate the state changes using monads you will also get points where you can add the observer mechanism inside the monad.

从你发布的代码判断你似乎实际上是做事件驱动的编程。因此,观察者模式是以面向对象语言获得事件驱动编程的典型方式。所以你有一个目标(事件驱动的程序设计)和一个工具在面向对象的世界(观察者模式)。如果你想使用功能编程的全部功能,你应该检查什么其他方法可用于实现这个目标,而不是直接从面向对象的世界移植工具(它可能不是功能语言的最佳选择)。只需检查这里提供的其他工具,你可能会找到更适合你的目标的东西。

Judging from the code you posted it seems that you are actually doing event driven programming. So the observer pattern is a typical way to get event driven programming in Object oriented languages. So you have a goal (event driven programming) and a tool in the object oriented world (observer pattern). If you want to use the full power of functional programming you should check what other methods are available for achieving this goal instead of directly porting the tool from the object oriented world (it might not be the best choice for a functional language). Just check what other tools are available here and you will probably find something that fits your goals much better.

这篇关于如何以纯功能方式实现观察者设计模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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