Archive for August 17th, 2008

h1

ObjectFactory without if-else オブジェクトファクトリ If-elseを使わないで

August 17, 2008

As I was developing software, I came to a situation where I needed to build a factory class. Based on the request, it needs to create an appropriate object. I don’t like a long if-else and initialization code. I came up an idea to use listener and implements an Interface that contains onCreate method. With this way, each target object can instantiate itself with implementation of that interface. The factory class simply calls the onCreate method for every listener within for loop. If the object is returned, the factory class simply returns that object.

 

In summary, there are two good points: one is you don’t need to write if-else statements; second, you can write initialization code within each class itself.

 

ソフトウェアを書いているとき、ファクトリクラスを作らなくてはいけなくなった。リクエストによって、正しいオブジェクトを新たに作らなくてはいけない。長たらしい、If-elseと初期化コードは書きたくない。それよりも、リスナーとOnCreate メソッドを含むインターフェースを使う方法がうかぶ。これにより、ターゲットとなるオブジェクト自身が新たな自分自身を作ることが出来る。ファクトリクラスは、ただループの中で、順々にリスナーのOnCreateメソッドを呼べばよい。ファクトリクラスは新しいオブジェクトが返された時に、それをリクエストしたオブジェクトに返せばよい。

 

これにより2つの利点がある。ひとつはIf-elseをつかわなくてもよい。もうひとつは、初期化コードが、クラス自身の中で定義できる。