简单工厂模式vs工厂方法模式

简单工厂要添加新类时,得在工厂类里面修改,添加判断生成新类的条件,这样破坏了开放-封闭的原则,内部改动,但是好处是,判断选择生成哪种类的对象交给了简单工程,而不是客户端这里

而工厂方法模式改良了简单工厂模式,每种类对象对应了一个生成该类对象的工厂类,当添加新类时,只要写个新类,再写个生成这个新类对象的工厂类,不需改内部代码,满足开放-封闭原则,缺点是生成什么类型的对象就得选用什么类型的工厂,这个选择交给了客户端,没有封装起来

//factory.h
#ifndef _FACTORY_H_
#define _FACTORY_H_

#include <iostream>
#include <string>
using namespace std;

class Leifeng
{
    public:
        void Wash()
        {
            cout << "洗衣服" << endl;
        }
        void Sweep()
        {
            cout << "扫地" << endl;
        }
        void BuyRice()
        {
            cout << "买米" << endl;
        }
        virtual void call() = 0;
        
};

class Ungraduate: public Leifeng
{
    public:
        void call()
        {
            cout << "我是大学生" << endl;
        }
};

class Volunteer: public Leifeng
{
    public:
        void call()
        {
            cout << "我是志愿者" << endl;
        }
};

class Factory
{
    public:
        static Leifeng *create(string &type)
        {
            Leifeng *person = NULL;
            if(type.compare("大学生") == 0)
                person = new Ungraduate();
            else if(type.compare("志愿者") == 0)
                person = new Volunteer();
            return person;
        }
};

class iFactory
{
    public:
        virtual Leifeng *createLeifeng() = 0;
};

class UngraduateFactory: public iFactory
{
    public:
        Leifeng *createLeifeng()
        {
            return new Ungraduate();
        }
};

class VolunteerFactory: public iFactory
{
    public:
        Leifeng *createLeifeng()
        {
            return new Volunteer();
        }
};
#endif


 

#include <iostream>
#include <cstdio>
#include "factory.h"
using namespace std;

int main()
{
       string type1("大学生");
    string type2("志愿者");
    Leifeng *p = NULL;
    p = Factory::create(type1);
    if(p != NULL)
    {
        p->call();
        p->Sweep();
        p->Wash();
        p->BuyRice();
        delete p;
        p = NULL;
    }
    cout << endl << endl;
    iFactory *f = NULL;
    if(type2.compare("大学生") == 0)
        f = new UngraduateFactory();
    else if(type2.compare("志愿者") == 0)
        f = new VolunteerFactory();
    if(f != NULL)
    {
        p = f->createLeifeng();
        p->call();
        p->Sweep();
        p->Wash();
        p->BuyRice();
        delete p;
        p = NULL;
        delete f;
        f = NULL;
    }
        
   
    return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值