一个对象的构建比较复杂,将一个对象的构建和对象的表示进行分离!!!
代码如下:
#include<iostream>
#include<string>
using namespace std;
class House{
public:
void setDoor(string door){
this->m_door = door;
}
void setWall(string wall){
this->m_wall = wall;
}
void setWindow(string window){
this->m_window = window;
}
public:
string getDoor(){
return m_door;
}
string getWall(){
return m_wall;
}
string getWindow(){
return m_window;
}
private:
string m_door;
string m_wall;
string m_window;
};
//请工程队来建造房子
class Build{
public:
House *setHouse(){
}
private:
};
int main(void){
//这样写不好,是客户直接造房子;
House *house = new House;
house->setDoor("门");
house->setWall("墙面");
house->setWindow("窗口");
delete house;
return 0;
}
只能生产一个产品;
代码如下:
#include<iostream>
using namespace std;
class Fruit;
class AbstractFactory{
public:
virtual Fruit *CreateBanana() = 0;
virtual Fruit *CreateApple() = 0;
private:
};
class Fruit{
public:
virtual void sayname() = 0;
private:
};
class NorthBanana : public Fruit{
public:
virtual void sayname(){
cout<<"我是北方香蕉"<<endl;
}
};
class NorthApple : public Fruit{
public:
virtual void sayname(){
cout<<"我是北方苹果"<<endl;
}
};
class SouthBanana : public Fruit{
public:
virtual void sayname(){
cout<<"我是南方香蕉"<<endl;
}
};
class SouthApple : public Fruit{
public:
virtual void sayname(){
cout<<"我是南方苹果"<<endl;
}
};
class NorthFactory : public AbstractFactory{
public:
virtual Fruit *CreateBanana(){
return new NorthBanana;
}
virtual Fruit *CreateApple(){
return new NorthApple;
}
private:
};
class SouthFactory : public AbstractFactory{
public:
virtual Fruit *CreateBanana(){
return new SouthBanana;
}
virtual Fruit *CreateApple(){
return new SouthApple;
}
private:
};
int main(void){
Fruit *fruit = NULL;
AbstractFactory *af = NULL;
//---------------------------
af = new SouthFactory;
fruit = af->CreateApple();
fruit->sayname();
fruit = af->CreateBanana();
fruit->sayname();
//---------------------------
af = new NorthFactory;
fruit = af->CreateApple();
fruit->sayname();
fruit = af->CreateBanana();
fruit->sayname();
delete af;
return 0;
}
运行结果:
抽象模式
- 缺点:抽象工厂的产品线都被写死了;只能生产这2种产品;