基本的设计模式分类:
创建型模式:负责对象的创建
结构型模式:处理类与对象之间的组合,可以解决继承依赖性的问题
行为型模式:类与对象交互中的职责分配,可以解决组件间如何交互,隔离变化
简单工厂模式(SimpleFactory)
优点:
1.隐藏了对象创建的细节,将产品延迟到子类中实现
2.方便添加新的子类产品,只需要修改工厂类传递的值即可
3.遵循依赖倒转的原则
缺点:
1.要求子类的类型差不多,使用方法都一样
2.违背了开放-封闭原则
代码实现:
SimpleFactory.h
#ifndef SIMPLEFACTORY_H
#define SIMPLEFACTORY_H
namespace SimpleFactory {
enum ClassType
{
aType = 0,
bType = 1,
cType = 2
};
class Base
{
public:
Base(){}
~Base(){}
virtual void show();
};
class A : public Base
{
public:
A(){}
~A(){}
void show();
};
class B : public Base
{
public:
B(){}
~B(){}
void show();
};
class SimpleFactory
{
public:
Base *CreateFactory(ClassType);
};
}
#endif // SIMPLEFACTORY_H
SimpleFactory.cpp
#include "simplefactory.h"
#include <iostream>
void SimpleFactory::Base::show()
{
std::cout << "this is Base" << std::endl;
}
void SimpleFactory::A::show()
{
std::cout << "this is A" << std::endl;
}
void SimpleFactory::B::show()
{
std::cout << "this is B" << std::endl;
}
SimpleFactory::Base *SimpleFactory::SimpleFactory::CreateFactory(ClassType type)
{
switch(type)
{
case aType:
{
return new A;
}
case bType :
{
return new B;
}
case cType:
{
return new B;
}
default:
{
return NULL;
}
}
}
main.cpp
#include <iostream>
#include "simplefactory.h"
int main()
{
SimpleFactory::SimpleFactory factory;
SimpleFactory::Base *a = factory.CreateFactory(SimpleFactory::aType);
a->show();
SimpleFactory::Base *b = factory.CreateFactory(SimpleFactory::bType);
b->show();
SimpleFactory::Base *c = factory.CreateFactory(SimpleFactory::cType);
c->show();
return 0;
}