Functional equivalent of decorator pattern?

后端 未结 10 2090
悲&欢浪女
悲&欢浪女 2021-02-02 06:34

What is the functional programming equivalent of the decorator design pattern?

For example, how would you write this particular example in a functional style?

10条回答
  •  有刺的猬
    2021-02-02 07:23

    Something like this:

    class Window w where
        draw :: w -> IO ()
        description :: w -> String
    
    data VerticalScrollingWindow w = VerticalScrollingWindow w
    
    instance Window w => Window (VerticalScrollingWindow w) where
        draw (VerticalScrollingWindow w)
           = draw w >> drawVerticalScrollBar w  -- `drawVerticalScrollBar` defined elsewhere
        description (VerticalScrollingWindow w)
           = description w ++ ", including vertical scrollbars"
    

提交回复
热议问题