简单工厂:将对象的创建封装在子类当中,客户不需要去手动创建对象,只需要调用一些接口传递不同的类型参数来创建对象。但是在一个工厂里 存在多种产品,会导致工厂的频繁修改
工厂方法:实现了不同的产品存在于不同的工厂,使其解耦
抽象工厂:实现了不同的工厂里面不止一种产品
简单工厂:一个工厂生产奥迪车,宝马车
class Car
{
public:
virtual void Show() = 0;
};
class Audi : public Car
{
public:
void Show()
{
cout << "奥迪 car" << endl;
}
};
class BWM : public Car
{
public:
void Show()
{
cout << "宝马 car" << endl;
}
};
enum CarType
{
bwm, audi
};
class Factory
{
public: Car* CreateCar(CarType t)
{
switch (t)
{
case 0:
return new BWM();
break;
case 1:
return new Audi();
break;
defualt:
cerr << "error" << t<< endl;
exit(1);
}
}
};
int main()
{
Factory* fa = new Factory();
Car* a = fa->CreateCar(bwm);
Car* b = fa->CreateCar(audi);
a->Show();
b->Show();
return 0;
}
工厂方法:奥迪工厂创建奥迪车,宝马工厂创建宝马车
class Car
{
public:
virtual void Show() = 0;
};
class Audi : public Car
{
private:std::string name;
public:
Audi(std::string a)
{
name = a;
}
void Show()
{
cout << "奥迪 car" << name<<endl;
}
};
class BWM : public Car
{
private:std::string name;
public:
BWM(std::string a)
{
name = a;
}
void Show()
{
cout << "宝马 car" <<name<< endl;
}
};
class Factory
{
public: virtual Car* CreateCar(string name) = 0;
};
class BwmFactory :public Factory
{
public:
Car* CreateCar(std::string name)
{
return new BWM(name);
}
};
class AudiFactory :public Factory
{
public:
Car* CreateCar(std::string name)
{
return new Audi(name);
}
};
int main()
{
BwmFactory bw;
std::string name("shining");
Car*p=bw.CreateCar(name);
p->Show();
AudiFactory cw;
Car* p1 = cw.CreateCar(name);
p1->Show();
return 0;
}
宝马工厂生产宝马车以及宝马灯,奥迪工厂生产奥迪车奥迪灯,一个工厂生产产品簇,而非单个产品
class Car
{
public:
virtual void Show() = 0;
};
class Audi : public Car
{
private:std::string name;
public:
Audi(std::string a)
{
name = a;
}
void Show()
{
cout << "奥迪 car" << name << endl;
}
};
class BWM : public Car
{
private:std::string name;
public:
BWM(std::string a)
{
name = a;
}
void Show()
{
cout << "宝马 car" << name << endl;
}
};
class Led
{
public:
virtual void Show() = 0;
};
class AudiLed : public Led
{
private:std::string name;
public:
AudiLed(std::string a)
{
name = a;
}
void Show()
{
cout << "奥迪 Led" << name << endl;
}
};
class BWMLed : public Led
{
private:std::string name;
public:
BWMLed(std::string a)
{
name = a;
}
void Show()
{
cout << "宝马 Led" << name << endl;
}
};
class Factory
{
public: virtual Car* CreateCar(string name) = 0;
};
class BwmFactory :public Factory
{
public:
Car* CreateCar(std::string name)
{
return new BWM(name);
}
Led* CreateLed(std::string name)
{
return new BWMLed(name);
}
};
class AudiFactory :public Factory
{
public:
Car* CreateCar(std::string name)
{
return new Audi(name);
}
Led* CreateLed(std::string name)
{
return new AudiLed(name);
}
};
int main()
{
BwmFactory bw;
std::string name("shining");
Car* p = bw.CreateCar(name);
Led* l1 = bw.CreateLed("宝马大灯");
p->Show();
l1->Show();
AudiFactory cw;
Car* p1 = cw.CreateCar(name);
Led* l11 = bw.CreateLed("奥迪大灯");
p1->Show();
l11->Show();
return 0;
}