ファクトリメソッドモデル(ファクトリメソッド)(RPM)

コンセプト

オブジェクトを作成するためのインターフェイスを定義しますが、サブクラスが技術をインスタンス化するクラスを決めましょう。そのサブクラスを遅らせるために、クラスのインスタンスを作成するファクトリメソッド。

モード構造

1559921156257

シンプルな工場のパターン比較

私たちは、計算の新しいメソッドを追加する必要がある場合は、電卓の例に戻って、単純なファクトリパターンを取得し、我々は、オペレータのサブクラスを追加する必要がある、と判断するファクトリメソッドにCaseステートメントに参加しました。クローズドの原則 - これは明らかに、オープンに反しています。

したがって、ファクトリメソッドパターン依存逆原理、抽象ファクトリクラス唯一の方法は、ファクトリメソッド抽象製品を作成することであるインターフェイスに係ります。植物工場のクラスへの単純なパターンの植物抽象インタフェースのオブジェクトおよび特定の生産工場の複数ように、その後、コンクリートを製造するために、すべてのクラスファクトリは、このインタフェースを実装しました。

下図のように:

1559922092613

パターンと分析の例

#include <string>
#include <iostream> using namespace std; class LeiFeng { public: virtual void Sweep() { cout << "LeiFeng sweep" << endl; } }; //学雷锋的学生,对应于ConcreteProduct class Student : public LeiFeng { public: virtual void Sweep() { cout << "Student sweep" << endl; } }; //学雷锋的志愿者,对应于ConcreteProduct class Volunteer : public LeiFeng { public: virtual void Sweep() { cout << "Volunteer sweep" << endl; } }; //工厂抽象基类 Creator class LeiFengFactory { public: virtual LeiFeng * CreateLeiFeng() { return new LeiFeng(); } }; //工厂具体类 class StudentFactory : public LeiFengFactory { public: virtual LeiFeng * CreateLeiFeng() { return new Student(); } }; //工厂具体类 class VolunteerFactory : public LeiFengFactory { public: virtual LeiFeng* CreateLeiFeng() { return new Volunteer(); } }; int main() { LeiFengFactory * factory = new LeiFengFactory(); LeiFeng * student = new Student(); LeiFeng * volunteer = new Volunteer(); student->Sweep(); volunteer->Sweep(); delete factory; delete student; delete volunteer; return 0; }

、クライアントの実装を決定する移動元のクラスを変更しない新しい機能を追加するには、クライアントを直接変更することができます。

おすすめ

転載: www.cnblogs.com/strugglerisnd/p/10990337.html