iT邦幫忙

2022 iThome 鐵人賽

DAY 18
0
自我挑戰組

Ruby OOP to Oops !n 30系列 第 18

IT 邦鐵人賽 Day 18-Decorator

  • 分享至 

  • xImage
  •  

裝飾器(Decorator)

目的:

將額外權責動態附加於物件身上,不必衍生子類別即可彈性增廣功能

結構:

https://ithelp.ithome.com.tw/upload/images/20221003/20151094ydovv6kKuA.png

程式碼範例:

class Component
  def operation
    raise NotImplementedError, "#{self.class} has not implemented method '#{__method__}'"
  end
end

class ConcreteComponent < Component
  def operation
    'ConcreteComponent'
  end
end

class Decorator < Component
  attr_accessor :component

  def initialize(component)
    @component = component
  end

  def operation
    @component.operation
  end
end

class ConcreteDecoratorA < Decorator
  def operation
    "ConcreteDecoratorA(#{@component.operation})"
  end
end

class ConcreteDecoratorB < Decorator
  def operation
    "ConcreteDecoratorB(#{@component.operation})"
  end
end

def client_code(component)
  print "RESULT: #{component.operation}"
end

simple = ConcreteComponent.new
puts 'Client: I\'ve got a simple component:'
client_code(simple)
puts "\n\n"


decorator1 = ConcreteDecoratorA.new(simple)
decorator2 = ConcreteDecoratorB.new(decorator1)
puts 'Client: Now I\'ve got a decorated component:'
client_code(decorator2)

解釋

這裡之所以不用繼承的原因在於,過多的組合會產出太多子類別繼承,而且繼承是屬於靜態(無法在過程中改變物件行為)所以使用組合方式進行

文章不定期更新!(umm ... 最近比較忙碌所以沒辦法紀錄太多,但會在之後陸續補充與將內容完整

感謝大家 如有問題,再煩請大家指教!


上一篇
IT 邦鐵人賽 Day 17 - Composite
下一篇
IT 邦鐵人賽 Day 19-Facade
系列文
Ruby OOP to Oops !n 3020
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言