设计模式学习:抽象工厂模式

本文介绍了抽象工厂模式的概念及其应用场景,并通过一个中餐与西餐产品的示例代码详细展示了该模式的具体实现过程。抽象工厂模式是一种更为强大的工厂方法模式,适用于需要创建一系列相关或相互依赖对象的复杂场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

抽象工厂模式是有多个抽象产品时,使用的工厂模式。抽象工厂模式可以向客户端提供接口,使用户在不指定具体产品的情况下,创建多个产品族中产品的对象。

下面我们用一个例子来说明抽象工厂模式,再下面的例子中,有两个产品族:中餐和西餐。产品族中有产品主食和甜点:

#include "stdafx.h"
#include <iostream>

using namespace std;

// 抽象产品接口
class Staple
{
public:
    virtual void Show() = 0;
};

class Dessert
{
public:
    virtual void Show() = 0;
};

// 产品族1,中餐
class RiseStaple : public Staple
{
public:
    void Show()
    {
        cout << "im rice; staple of chinese food" << endl;
    }
};

class SpringRollDessert : public Dessert
{
public:
    void Show()
    {
        cout << "im sprint roll; dessert of chinese food" << endl;
    }
};

// 产品族2,西餐
class SteakStaple : public Staple
{
public:
    void Show()
    {
        cout << "im steak; staple of western food" << endl;
    }
};

class PieDessert : public Dessert
{
public:
    void Show()
    {
        cout << "im pie; staple of western food" << endl;
    }
};

// 抽象工厂类
class Factory
{
public:
    virtual Staple* GetStaple() = 0;
    virtual Dessert* GetDessert() = 0;
};

// 具体工厂类
class ChineseFoodFactory : public Factory
{
public:
    Staple* GetStaple()
    {
        return new RiseStaple();
    }
    Dessert* GetDessert()
    {
        return new SpringRollDessert();
    }
};

class WesternFoodFacotry : public Factory
{
public:
    Staple* GetStaple()
    {
        return new SteakStaple();
    }
    Dessert* GetDessert()
    {
        return new PieDessert();
    }
};

void PrepareFood(Factory* factory)
{
    Staple* staple = factory->GetStaple();
    Dessert* dessert = factory->GetDessert();
    staple->Show();
    dessert->Show();

    cout << "done..." << endl;

    delete factory;
    delete staple;
    delete dessert;
}

int main()
{
    PrepareFood(new ChineseFoodFactory());
    PrepareFood(new WesternFoodFacotry());

    system("pause");

    return 0;
}

代码执行结果如下:

im rice; staple of chinese food
im sprint roll; dessert of chinese food
done…
im steak; staple of western food
im pie; staple of western food
done…

从例子中可以看出,抽象工厂模式有点像是工厂方法模式的加强版。工厂方法模式每个具体工厂只能生成单一的产品,但是抽象方法模式一个具体工厂可以生产多个产品。所以,工厂方法模式比较适合产品结构单一的场景,但是抽象工厂模式适合于产品结构复杂的场景;每个具体工厂提供一组相关或者相互依赖的对象

抽象工厂模式也保证了多个对象一起工作的时候,这些对象一定是一个产品族中的,比如上例中,我们要吃中餐就所有的食物都是中餐,不会牛排和春卷一起混着吃。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值