[img]C:\Documents and Settings\Administrator\桌面\编程\设计模式\Factory.jpg[/img]
刚开始学习设计模式,还不是很懂,慢慢来吧,首先应该是Factory Pattern,下面是代码:
Product.h
Product.cpp
Factory.h
Factory.cpp
main.cpp
刚开始学习设计模式,还不是很懂,慢慢来吧,首先应该是Factory Pattern,下面是代码:
Product.h
#ifndef _PRODUCT_H_
#define _PRODUCT_H_
#include <iostream>
using namespace std;
class Product
{
public:
virtual ~Product()=0;
protected:
Product();
private:
};
class ConcreteProductA :public Product
{
public:
~ConcreteProductA();
ConcreteProductA();
protected:
private:
};
class ConcreteProductB :public Product
{
public:
~ConcreteProductB();
ConcreteProductB();
protected:
private:
};
#endif
Product.cpp
#include "Product.h"
#include <iostream>
using namespace std;
Product::Product(){}
Product::~Product(){}
ConcreteProductA::ConcreteProductA(){
cout << "ConcreteProductA....." <<endl;
}
ConcreteProductA::~ConcreteProductA(){
}
ConcreteProductB::ConcreteProductB(){
cout << "ConcreteProductB....." <<endl;
}
ConcreteProductB::~ConcreteProductB(){
}
Factory.h
#ifndef FACTORY_H_
#define FACTORY_H_
#include "Product.h"
#include <iostream>
using namespace std;
class Product;
class Factory
{
public:
virtual ~Factory()=0;
virtual Product* creatProductA()=0;
virtual Product* creatProductB()=0;
protected:
Factory();
private:
};
class ConcreteFactory:public Factory
{
public:
ConcreteFactory();
~ConcreteFactory();
Product* creatProductA();
Product* creatProductB();
protected:
private:
};
#endif
Factory.cpp
#include "Factory.h"
#include "Product.h"
#include <iostream>
using namespace std;
Factory::Factory(){
}
Factory::~Factory(){
}
ConcreteFactory::ConcreteFactory(){
cout << "ConcreteFactory..."<<endl;
}
ConcreteFactory::~ConcreteFactory(){
}
Product* ConcreteFactory::creatProductA(){
return new ConcreteProductA();
}
Product* ConcreteFactory::creatProductB(){
return new ConcreteProductB();
}
main.cpp
#include <iostream>
#include "Factory.h"
#include "Product.h"
using namespace std;
int main(){
Factory* factory = new ConcreteFactory();
Product* productA = factory->creatProductA();
Product* productB = factory->creatProductB();
return 0;
}