• 设计模式16——工厂模式


    抽象工厂中,不同的对象通过的不同的输入符号来判断。当要添加新的类时,需要修改工厂类,不利于扩展。

    工厂模式中,不同的类由不同的工厂创建出来,相互之间不受影响。

    #ifndef Factory_H_H
    #define Factory_H_H
    
    #include <iostream>
    #include <string>
    using namespace std;
    
    class Person{
    protected:
        string strName;
    public:
        Person(){
        }
    
        void show(){
            cout << "This is " << strName << endl;
        }
    };
    
    class Student : public Person{
    public:
        Student(){
            strName = "Student";
        }
    };
    
    class Teacher : public Person{
    public:
        Teacher(){
            strName = "Teacher";
        }
    };
    
    class Factory{
    public:
        virtual Person *create() = 0;
    };
    
    class StudentFactory : public Factory{
    public:
        Person *create(){
            return new Student();
        }
    };
    
    class TeacherFactory : public Factory{
    public:
        Person *create(){
            return new Teacher();
        }
    };
    
    
    void FactoryTest(){
        Factory *factory1 = new StudentFactory();
        factory1->create()->show();
    
        Factory *factory2 = new TeacherFactory();
        factory2->create()->show();
    
    }
    
    #endif
  • 相关阅读:
    学习总结
    HBase简要介绍
    分布式文件系统HDFS
    Hadoop基础安装和使用
    大数据的学习基础
    学习总结
    Python-爬取豆瓣电影信息并存到mysql
    python爬虫回顾与总结
    正则表达式-爬虫获取豆瓣电影超链接
    BeautifulSoup相关学习
  • 原文地址:https://www.cnblogs.com/MiniHouse/p/4589688.html
Copyright © 2020-2023  润新知