Dh01-Simple Factory mode

Source: Internet
Author: User

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:

    1. Factory class role: The core of the model, with certain business logic and judgment logic. As the class in the exampleAnimalSpecies
    2. Abstract Product Role: The parent class of the specific product inheritance or implementation interface. As the class in the exampleAnimal
    3. 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;}


Simplified design mode (Chinese version): Http://wenku.baidu.com/view/8fb442ce0508763231121206.html?from=search

Dh01-Simple Factory mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.