标签:col head pdf c51 asm new DRC xsl gimp
抽象基类:
1) Product:创建出来的对象的抽象基类.
2) Factory 创建对象的工厂方法的抽象基类.
接口函数:
1) Creator::FactoryMethod:纯虚函数,由派生类实现,创建出对应的 Product.
解析:
在这个模式中,有两个抽象基类,一个是 Product 为创建出来的对象的抽象基类,一个是 Factory 是工厂的抽象基类,在互相协作的时候都是由相应的 Factory 派生类来生成Product的派生类,也就是说如果要新增一种Product那么也要对应的新增一个 Factory,创建的过程委托给了这个 Factory.也就是说一个 Factory和一个 Product 是一一对应的关系.
备注:
设计模式的演示图上把Factory类命名为Creator,下面的实现沿用了这个命名.
|
|
#ifndef __FACTORY_H__
#define __FACTORY_H__
#include<iostream>
using namespace std;
class product
{
public:
product(){ cout<<"product()"<<endl; }
virtual ~product(){ cout<<"~product()"<<endl; }
};
class A
{
public:
A(){ cout<<"A()"<<endl; }
~A(){ cout<<"~A()"<<endl; }
};
class B
{
public:
B(){ cout<<"B()"<<endl; }
~B(){ cout<<"~B()"<<endl; }
};
class concreteproduct:public product
{
public:
concreteproduct(A* pa,B* pb):_pa(pa),_pb(pb)
{
cout<<"concreteproduct()"<<endl;
}
~concreteproduct(){ cout<<"~concreteproduct()"<<endl; }
private:
A* _pa;
B* _pb;
};
class factory
{
public:
factory(){ cout<<"factory()"<<endl; }
// 抽象类
virtual product* create() = 0;
virtual ~factory(){ cout<<"~factory()"<<endl; }
};
class concretefactory:public factory
{
public:
concretefactory(){ cout<<"concretefactory()"<<endl; }
product* create();
~concretefactory(){ cout<<"~concretefactory()"<<endl; }
};
product* concretefactory::create()
{
cout<<"concretefactory::create()"<<endl;
A* pa = new A();
B* pb = new B();
product* pro = new concreteproduct(pa,pb);
return pro;
}
endif
|
#include<iostream>
#include"factory.h"
using namespace std;
int main()
{ // 工厂模式主要用来创建复杂对象
// 一个产品对应一个工厂类
factory* fac = new concretefactory();
product* pro = fac->create();
delete fac;
delete pro;
return 0;
}
|
标签:col head pdf c51 asm new DRC xsl gimp
原文地址:https://www.cnblogs.com/meihao1203/p/9368319.html