简单工厂
#include<iostream>
using namespace std;
class Car
{
public:
Car(string name):_name(name){}
virtual void show()=0;
protected:
string _name;
};
class BMW:public Car
{
public:
BMW(string name):Car(name){}
void show()
{
cout<<"获取一辆宝马汽车"<<_name<<endl;
}
};
class Audi:public Car
{
public:
Audi(string name):Car(name){}
void show()
{
cout<<"获取了一辆奥迪汽车"<<_name<<endl;
}
};
int main()
{
Car *p1= new BMW("X1");
Car *p2=new Audi("A6");
p1->show();
p2->show();
return 0;
}
#include<iostream>
#include<memory>
using namespace std;
class Car
{
public:
Car(string name):_name(name){}
virtual void show()=0;
protected:
string _name;
};
class Bmw:public Car
{
public:
Bmw(string name):Car(name){}
void show()
{
cout<<"获取一辆宝马汽车"<<_name<<endl;
}
};
class Audi:public Car
{
public:
Audi(string name):Car(name){}
void show()
{
cout<<"获取了一辆奥迪汽车"<<_name<<endl;
}
};
enum CarType
{
BMW,AUDI
};
class SimpleFactory
{
public:
Car *createCar(CarType ct)
{
switch(ct)
{
case BMW:
return new Bmw("X1");
case AUDI:
return new Audi("A6");
default:
cerr<<"参数传递错误"<<endl;
return nullptr;
}
}
};
int main()
{
unique_ptr<SimpleFactory> factory(new SimpleFactory());
unique_ptr<Car> p1(factory->createCar(BMW));
unique_ptr<Car> p2(factory->createCar(AUDI));
p1->show();
p2->show();
return 0;
}
工厂方法
#include<iostream>
#include<memory>
using namespace std;
class Car
{
public:
Car(string name):_name(name){}
virtual void show()=0;
protected:
string _name;
};
class Bmw:public Car
{
public:
Bmw(string name):Car(name){}
void show()
{
cout<<"获取一辆宝马汽车"<<_name<<endl;
}
};
class Audi:public Car
{
public:
Audi(string name):Car(name){}
void show()
{
cout<<"获取了一辆奥迪汽车"<<_name<<endl;
}
};
class Factory
{
public:
virtual Car *createCar(string name)=0;
};
class BMWFactory:public Factory
{
public:
Car *createCar(string name)
{
return new Bmw("X1");
}
};
class AudiFactory:public Factory
{
public:
Car *createCar(string name)
{
return new Bmw(name);
}
};
int main()
{
unique_ptr<Factory> bmwfty(new BMWFactory());
unique_ptr<Factory> audifty(new BMWFactory());
unique_ptr<Car> p1(bmwfty->createCar("X6"));
unique_ptr<Car> p2(audifty->createCar("A8"));
p1->show();
p2->show();
return 0;
}