使用C++写抽象工厂模式涉及到的一些问题

代码是摘自《C++高级编程第二版》

具体类图如下:

代码如下:

汽车类:

#include <iostream>

class Car
{
public:
	virtual void info() = 0;
};
class Ford : public Car
{
public:
	virtual void info() { std::cout<< "Ford" << std::endl; }
};
class Toyota : public Car
{
public:
	virtual void info() { std::cout<< "Ford" << std::endl; }
};
汽车工厂类:

#include "Car.h"

class CarFactory
{
public:
	CarFactory();
	Car* requestCar();
	int getNumCarsInProduction() const;
protected:
	virtual Car* createCar() = 0;
private:
	int mNumCarsInProduction;
};
class FordFactory : public CarFactory
{
protected:
	virtual Car* createCar();
};
class ToyotaFactory : public CarFactory
{
protected:
	virtual Car* createCar();
};
汽车工厂类中成员的具体定义:

#include "CarFactory.h"

CarFactory::CarFactory() : mNumCarsInProduction(0) {}

Car* CarFactory::requestCar()
{
	mNumCarsInProduction++;
	return createCar();
}
int CarFactory::getNumCarsInProduction() const
{
	return mNumCarsInProduction;
}
Car* FordFactory::createCar()
{
	return new Ford();
}
Car* ToyotaFactory::createCar()
{
	return new Toyota();
}

C++ Primer 4 中提到 派生类中虚函数的声明必须和基类中的定义方式完全匹配,但有一个例外:返回对基类型的引用或指针的虚函数,派生类中的虚函数可以返回基类函数所返回类型的派生类的引用或指针。说的就是CarFactory中的Car* createCar()函数成员,在派生类FordFactory和ToyotaFactory中的createCar中,返回的是各自类型的车对象的指针。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值