Created
September 4, 2022 13:22
-
-
Save okabe-yuya/14524670a99bc31bd0f3fce2f358409c to your computer and use it in GitHub Desktop.
design pattern in ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Iterator | |
def next | |
raise NotImplementedError.new("#{self.class}##{__method__} が実装されていません") | |
end | |
def has_next | |
raise NotImplementedError.new("#{self.class}##{__method__} が実装されていません") | |
end | |
end | |
class Aggregate < Iterator | |
def iterator | |
raise NotImplementedError.new("#{self.class}##{__method__} が実装されていません") | |
#FFmpeg等、エンコーダーに合わせた処理を実装する。 | |
end | |
end | |
class MyArray < Aggregate | |
attr_reader :list | |
def initialize(data_size) | |
@list = [nil] * data_size | |
@data_size = data_size | |
@pivot = 0 | |
end | |
def append(val) | |
throw 'index out of range' if @pivot > @data_size | |
@list[@pivot] = val | |
@pivot += 1 | |
end | |
def at(index) | |
@list[index] | |
end | |
def length | |
@data_size | |
end | |
def iterator | |
MyArrayIterator.new(self) | |
end | |
end | |
class MyArrayIterator < Iterator | |
def initialize(my_array) | |
@my_array = my_array | |
@index = 0 | |
end | |
def next_ | |
val = @my_array.at(@index) | |
@index += 1 | |
val | |
end | |
def has_next | |
@index < @my_array.length | |
end | |
end | |
array = MyArray.new(10) | |
10.times { |n| array.append(n + 1) } | |
iterator = array.iterator | |
while iterator.has_next do | |
val = iterator.next_ | |
puts val | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment