码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-11-06 14:56:05      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:设计模式初探   设计模式   c++   软件开发   抽象工厂   

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


适用性:

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

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

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

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


UML图:

bubuko.com,布布扣


依然写个小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;
};


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

标签:设计模式初探   设计模式   c++   软件开发   抽象工厂   

原文地址:http://blog.csdn.net/cloud_castle/article/details/40859345

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!