设计模式初探4——抽象工厂(Abstract Factory)

抽象工厂:为一个产品家族提供了统一的创建接口。当需要这个产品家族的某一系列的时候,可以从抽象工厂中选出相对系的系列来创建一个具体的工厂类别。


适用性:

一个系统要独立于它的产品的创建、组合和表示时。

一个系统要由多个产品系列中的一个来配置时。

当你要强调一系列相关的产品对象的设计以便进行联合使用时。

当你提供一个产品类库,而只想显示它们的接口而不是实现时。


UML图:



依然写个小Demo吧:

#include <stdlib.h>
#include <iostream>
#include <string>
using namespace std;

class Product
{
public:
    virtual generateContent() = 0;
    void displayMyself() {
        productContent = generateContent();
        cout << productContent << "\n";
    }
private:
    string productContent;	
};

class Shoes : public Product
{
public:
    string generateContent(){
        return "Shoes has been Created !";
    }
};

class Clothes : public Product
{
public:
    string generateContent(){
        return "Clothes has been Created !";
    }
};

class AbstractFactory
{
public:
    virtual Product* createProduct() = 0
};

class ShoesFactory
{
public:
    Product* createProduct(){ return new Shoes(); }
}

class ClothesFactory
{
public:
    Product* createProduct(){ return new Clothes(); }
}

int main(int argc, char* argv[])
{
    AbstractFactory *factory = new ShoesFactory();
    factory->createProduct()->displayMyself();
    factory = new ClothesFactory();
    factory->createProduct()->displayMyself();

    system("pause");
    return 0;
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值