Introduction to Patterns
The simple Factory mode, also known as the static factory method pattern, defines an interface for creating objects. Its main components are:
- Factory class role: The core of the model, with certain business logic and judgment logic. As the class in the example
AnimalSpecies
- Abstract Product Role: The parent class of the specific product inheritance or implementation interface. As the class in the example
Animal
- Specific product roles: the object created by the factory class is an instance of this role. such as the class in the example
Cat
,Dog
Class Diagram Analysis
Program code
#include <iostream>using namespace std;class Animal{public: virtual void showMessage()=0;//基类不在基类中实现纯虚函数的方法是在函数原型后加“=0”};class Cat :public Animal{public: Cat(){} void showMessage() { cout << "i am cat" << endl; }};class Dog :public Animal{public: Dog(){} void showMessage() { cout << "i am dog" << endl; }};class AnimalSpecies{public: Animal *createAnimal(const char *name) { if (strcmp(name, "cat")==0) //1、== 返回0 2、>返回正数 3、<返回负数 { return new Cat(); } else if (strcmp(name,"dog")==0) { return new Dog(); } }};int main(){ AnimalSpecies *as=new AnimalSpecies(); Animal *dog=as->createAnimal("dog"); Animal *cat = as->createAnimal("cat"); dog->showMessage(); cat->showMessage(); system("pause"); return 0;}
Resources
Simplified design mode (Chinese version): Http://wenku.baidu.com/view/8fb442ce0508763231121206.html?from=search
Dh01-Simple Factory mode