デザインパターン

デザインパターンdecorator

decoratorパターンです 継承を利用せずに、委譲を利用する 同じinterfaceを持つインスタンスを保持する 多段の継承を利用するより変更に強い class Icecream def get_name; end def how_sweet; end endclass VanillaIcecream def get_name return "バニラア…

デザインパターンcomposite

compositeパターンです 親子で同じインターフェイスを継承します class DirectoryEntry def remove; end endclass TestFile def initialize(name) @name = name end def remove puts @name + "を削除しました" end endclass TestDirectory def initialize(na…

デザインパターンstrategy

strategyパターンです ロジッククラスをポリモーフィズムで呼び出す class Human attr_accessor :name, :height, :weight, :age def initialize(name, height, weight, age) @name = name @height = height @weight = weight @age = age end endclass AgeCom…

デザインパターンbridge

bridgeパターンです 変更がある機能は委譲を使ってクラスに取込んでいます class Sorter def initialize(sorter) @sorter = sorter end def sort @sorter.sort end endclass QuickSort def sort # dummy sort 1000.times{ h = Hash.new puts "h" } end endcl…

デザインパターンabstract_factory

abdtract_factoryパターンです 利用するオブジェクトをごっそり入れ替えるときに利用します class HotPot def initialize end def add_soup(soup) @soup = soup end def add_main(protein) @protein = protein end def add_vegetables(vegetables) @vegetabl…

デザインパターンbuilder

builderパターンです 作成過程が同じで異なる表現形式の結果を得るためのパターン class SaltWater attr_accessor :water, :salt def initialize(water, salt) @water = water @salt = salt end end class SaltWaterBuilder def initialize @salt_water = Sa…

デザインパターンprototype

prototypeパターンです 中身が同じオブジェクトはコピーして使うtips メモリの節約ですね class Paper attr_accessor :name def initialize(name=nil) @name = name end def clone paper = Paper.new paper.name = @name return paper end def add(msg) @nam…

デザインパターンsingleton

singletonパターンです http://www.techscore.com/tech/DesignPattern/Prototype.html class RegisterNote def self.instance(arg) @@register_note ||= RegisterNote.new(arg) end def add_msg(msg) @msg = msg end def puts_msg puts @msg end def initial…

デザインパターンfactry_method

factory_methodパターンです http://www.techscore.com/tech/DesignPattern/FactoryMethod.html 主ロジックで使用する インスタンスをサブクラスで切り替えられるパターン これもよく見るパターンですね class Wood attr_accessor(:str) def initialize @str…

デザインパターンtemplate_method

template_methodパターンです http://www.techscore.com/tech/DesignPattern/TemplateMethod.html#dp3-3 アルゴリズム部分を個別の部品として抽象化して 部品の組み立てだけをスーパークラスとして実装する。 なんか結構使える場面がありそうですね。 class …

デザインパターン(iterator)

最近設計ではまることが多いので デザインパターンをrubyで復習することにしました。 ここ↓を参考にrubyで演習問題解いていきます。 http://www.techscore.com/tech/DesignPattern/index.html まずはiteratorから http://www.techscore.com/tech/DesignPatte…