なんだか、前回といい、今回といい、個人的なメモだな…。
 ごめん。

 「initializeが多重定義できない」のに、どうやって複数の生成方法を実装するか。
 考えたのだけど、「これは完璧だ!」というのが思いつかなかった。
 考えたのは二つあって、
1.FactoryMethodパターンを適応する
2.生成のためのクラスメソッド定義する。
である。

 両方とも欠点がある。
■案1の欠点
1.初期化していないProductクラスのインスタンス生成が、可能なこと。Creatorクラスを介さなくても、生成は可能だから。
2.無駄にクラス数が増える。

■案2の欠点
1.初期化していないProductクラスのインスタンス生成が、可能なこと。newをprivateに宣言できたらできるのだろうか? できるのかもしれないけれど、方法がわからない。
2.継承の時に面倒。クラスメソッドの呼び出しに対しては、ポリモルフィズムが生じない。

 ちなみに案2の方を書いてみると、次のような感じ。

class Product
 def self.factoryMethod
  return Product.new
 end

 def self.createA
  return detailInitializeA(self.factoryMethod)
 end
 def self.detailInitializeA(aInstance)
  # Aな初期化処理
  return aInstance
 end
 
 def self.createB
  return detailInitializeB(self.factoryMethod)
 end
 def self.detailInitializeB(aInstance)
  # Bな初期化処理
  return aInstance
 end

end
class ProductChild < Product
 def self.factoryMethod
  return ProductChild.new
 end

 #必ず上書き。もししないと、親クラスのfactoryMethodが呼ばれる。
 def self.createA
  return detailInitializeA(self.factoryMethod)
 end
 def self.detailInitializeA(aInstance)
  super
  # Aな初期化処理
  return aInstance
 end

 def self.createB
  return detailInitializeB(self.factoryMethod)
 end
 def self.detailInitializeB(aInstance)
  super
  # Bな初期化処理
  return aInstance
 end

end


begin
 a = ProductChild.createA
 print a, " "
end

コメント