zoukankan      html  css  js  c++  java
  • 设计模式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
  • 相关阅读:
    后端注册接口完善
    编写注册接口
    Git 多人开发及常见问题
    Git 常用命令
    GIT 的安装及配置SSH
    ORM查询方法(整理)
    HTTP的系列理解与整理
    Unity C# 反射
    C# 中的委托和事件
    Unity C# 运用 GetSaveFileName() 导出Excel文件
  • 原文地址:https://www.cnblogs.com/MiniHouse/p/4589688.html
Copyright © 2011-2022 走看看