ファクトリメソッド:
こんにちは、みなさん。私は、単純な工場と工場の方法との違いを探しています..私は構造上の違い(画像上の)を知っているが、私は、ユースケースの違いを理解して傾けます。例えば、これは、ファクトリメソッドの説明は次のとおりです。
ファクトリメソッドパターンでは、「IMobileFactory」と2つの具象実装の「NokiaFactory」と「IphoneFactory」と呼ばれる新しいインターフェイスを紹介します。これらの具体的なクラスは、オブジェクトの作成を制御します。
私の例では、クライアントは、Nokiaのオブジェクトをしたいです。だから、手順は以下の通りです。
1.The client will load a reference to ‘NokiaFactory’. But Client won’t refer the ‘NokiaFactory’ class directly like the Simple Factory pattern. The client refers the concrete implementation through an interface ‘IMobileFactory’.
2.Then the Client call the ‘CreateMobile()’ method that will return an object of type ‘IMobile’.
3.Here we have to inform the client the concrete implementation to be used through some configuration or parameters.
I can't understand the first step:
But Client won’t refer the ‘NokiaFactory’ class directly like the Simple Factory pattern. The client refers the concrete implementation through an interface ‘IMobileFactory’.
so client writes something like this:
IMobileFactory factory = LoadFactory("NokiaFactory");
so why is that useful and better? what's the benefit? why shouldn't I just write this:
NokiaFactory factory = new NokiaFactory();
or what about that:
IMobileFactory factory = new NokiaFactory();
So your question is about comparing this design #1:
IMobileFactory factory = LoadFactory("NokiaFactory");
to this design #2:
NokiaFactory factory = new NokiaFactory(); // or:
IMobileFactory factory = new NokiaFactory();
As you see the biggest difference is that, while the client in the design #1 does not know about any concrete type like NokiaFactory
or IPhoneFactory
, the client in the design #2 does.
The downside of knowing about concrete things like NokiaFactory
or IPhoneFactory
should be well-known. If you want to make changes to these types, for example, you want to add a new method to NokiaFactory
and this method is not a part of the IMobileFactory
interface, then the client code will be affected unnecessarily. The client does not care about the new method, but its code must be recompiled/redeployed.
UPDATE
To explain more.
For example, a new method named Foo
is added to the NokiaFactory
class:
class NokiaFactory {
// old code
public void Foo() { ... }
}
Foo
方法ではありませんIMobileFactory
インターフェイスそれはに追加されたNokiaFactory
方法が必要で別のクライアントがありますので、そのクライアントが依存して幸せであるNokiaFactory
クラス。言い換えれば、そのクライアントはからの変更歓迎NokiaFactory
クラスは、しかし、最初のクライアントはないでしょう。