您的位置:首页 > 其它

设计模式系列(9)简单工厂模式

2017-06-08 11:11 267 查看
1.什么是简单工厂模式

  简单工厂模式属于类的创建型模式,又叫做静态工厂方法模式。通过专门定义一个类来负责创建其它类的实例,被创建的实例通常都具有共同的父类。

2.模式中包含的角色及其职责

1) 工厂(Creator)角色

  简单工厂模式的核心,它负责实现创建所有实例的内部逻辑。工厂类可以被外外界直接调用,创建所需要的产品对象。

1) 抽象(Product)角色

  简单工厂模式所创建的所有对象的父类,它负责描述所共有的公共接口。

2) 具体产品(Concrete Product)角色

  简单工厂模式所创建的具体实例对象。

                                 


                                                                      简单工厂模式 UML类图

3.简单工厂模式的优缺点

  在这个模式中,工厂类是整个模式的关键所在。它包含必要的判断逻辑,能够根据外界给定的信息,决定应该创建哪个具体类的对象。用户在使用时可以直接根据工厂类去创建所需要的实例,而无需了解这些对象是如何创建以及如何组织。有利于整个软件体系结构的优化。不难发现,简单工厂的缺点也正体现在工厂类上,由于工厂类集中体现了所有实例的创建逻辑,所有高内聚方面做的并不好。另外,当系统中的具体产品类不断增多时,可能出现要求工厂类要做相应的修改,扩展性并不好。

4.示例代码, 通过工厂类创建不同的水果:

simple_factory.cpp

#ifndef SIMPLE_FACTORY_H
#define SIMPLE_FACTORY_H

class Fruit
{
public:
virtual void getFruit() = 0;
protected:

private:

};

class Banana : public Fruit
{
public:
virtual void getFruit();
protected:
private:
};

class Apple : public Fruit
{
public:
virtual void getFruit();

protected:
private:
};

class Factory
{
public:
Fruit *create(char *p);
};

#endif // SIMPLE_FACTORY_H


simple_factory.cpp

#ifndef SIMPLE_FACTORY_CPP
#define SIMPLE_FACTORY_CPP

#include <iostream>
#include <simple_factory.h>
#include <string.h>

using namespace std;

void Banana::getFruit()
{
cout << "banana" << endl;
}

void Apple::getFruit()
{
cout << "Apple" << endl;
}

Fruit* Factory::create(char *p)
{
if(0 == strcmp(p, "banana"))
{
return new Banana;
}
else if(0 == strcmp(p, "apple"))
{
return new Apple;
}
else
{
return NULL;
cout << "no support ..." << endl;
}

}

#endif // SIMPLE_FACTORY_CPP


main.cpp

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

using namespace std;

int main()
{

Factory *f = new Factory;

Fruit *fruit = NULL;

//工厂生产香蕉
fruit = f->create("banana");
fruit->getFruit();
delete fruit;

//工厂生产苹果
fruit = f->create("apple");
fruit->getFruit();
delete fruit;

delete f;

return 0;
}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: