设计模式(C++)——抽象工厂模式

抽象工厂模式

抽象工厂是负责多个配套类的统一创建,某些类我希望他们配套使用,比如说衣服,当我指定了要穿西装,如果我要穿衣服(?),那么我希望创建的是配套的西装上衣和西装裤子,而不是西装上衣配个大裤衩子。

// Coat.h
//衣服抽象类
#pragma once
class Coat
{
public:
    virtual void wear() = 0;
}
//Pants.h
//裤子抽象类
#pragma once
class Pant
{
public:
    virtual void wear() = 0;
}
//CoatImpl.h
#pragma once
#include "Coat.h"
#include <iostream>
//西装上衣
class SuitCoat final : public Coat
{
public:
    virtual void wear() override
    {
        std::cout << "Wear suit coat." << std::endl;
    }
}
//背心
class Tank final : public Coat
{
public:
    virtual void wear() override
    {
        std::cout << "Wear tank." << endl;
    }
}
//PantsImpl.h
#pragma once
#include "Pants.h"
#include <iostream>
//西装裤子
class SuitPants final : public Pants
{
public:
    virtual void wear() override
    {
        std::cout << "Wear suit pants." << std::endl;
    }
}
//运动裤
class SportsShorts final : public Pants
{
public:
    virtual void wear() override
    {
        std::cout << "Wear sports shorts." << endl;
    }
}
//Factory.h
#pragma once
#include "Coat.h"
#include "Pants.h"
//抽象工厂类
class AbstractFactory
{
public:
    virtual Coat*  getCoat()  = 0;
    virtual Pants* getPants() = 0;
}
//西装工厂
class SuitFactory final : public AbstractFactory
{
public:
    virtual Coat*  getCoat()  override;
    virtual Pants* getPants() override;
}
//运动装工厂
class SportsFactory final : public AbstractFactory
{
public:
    virtual Coat*  getCoat()  override;
    virtual Pants* getPants() override;
}
//Factory.cpp
#include "Factory.h"
#include "CoatImpl.h"
#include "PantsImpl.h"

virtual Coat* SuitFactory::getCoat() override
{
    return new SuitCoat();
}
virtual Pants* SuitFactory::getPants() override
{
    return new SuitPants();
}

virtual Coat* SportsFactory::getCoat() override
{
    return new Tank();
}
virtual Pants* SportsFactory::getPants() override
{
    return new SportsShorts();
}
//main.cpp
#include "Factory.h"

int main()
{
    //想穿西装
    AbstractFactory* f = new SuitFactory();
    Coat* coat = f->getCoat();
    coat->wear();
    Pants* pants = f->getPants();
    pants->wear();
    
    delete coat;
    coat = nullptr;
    delete pants;
    pants = nullptr;
    delete f;
    f = nullptr;
    
    //要去打球
    f = new SportsFactory();
    coat = f->getCoat();
    coat->wear();
    pants = f->getPants();
    pants->wear();
    
    delete coat;
    coat = nullptr;
    delete pants;
    pants = nullptr;
    delete f;
    f = nullptr;
    
    return 0;
}

可以看到,抽象工厂模式,当指定了工厂之后,生产的类一定配套。所以抽象工厂模式是负责生产多个配套使用的类。
抽象工厂和工厂的区别,在于工厂模式只负责一种对象的生成,而抽象工厂负责多个配套类的生成。

原创文章 34 获赞 41 访问量 5941

猜你喜欢

转载自blog.csdn.net/qq_44844115/article/details/106094211