Подробнее на 👉 refactoring.guru
#include <iostream>
#include <string>
class Car {
public:
virtual void info() = 0;
};
class CarFactory {
public:
virtual Car* createCar() = 0;
};
class SedanCar : public Car {
public:
void info() { std::cout << "This is a Sedan car" << std::endl; }
};
class SportCar : public Car {
public:
void info() { std::cout << "This is a Sport car" << std::endl; }
};
class SedanCarFactory : public CarFactory {
public:
Car* createCar() { return new SedanCar(); }
};
class SportCarFactory : public CarFactory {
public:
Car* createCar() { return new SportCar(); }
};
int main() {
CarFactory* sedanFactory = new SedanCarFactory();
Car* sedanCar = sedanFactory->createCar();
sedanCar->info();
CarFactory* sportFactory = new SportCarFactory();
Car* sportCar = sportFactory->createCar();
sportCar->info();
delete sedanCar;
delete sedanFactory;
delete sportCar;
delete sportFactory;
return 0;
}
Будет напечатано:
This is a Sedan car This is a Sport car
abstract class Car {
void info();
}
abstract class CarFactory {
Car createCar();
}
class SedanCar implements Car {
void info() {
print('This is a Sedan car');
}
}
class SportCar implements Car {
void info() {
print('This is a Sport car');
}
}
class SedanCarFactory implements CarFactory {
Car createCar() {
return SedanCar();
}
}
class SportCarFactory implements CarFactory {
Car createCar() {
return SportCar();
}
}
void main() {
CarFactory sedanFactory = SedanCarFactory();
Car sedanCar = sedanFactory.createCar();
sedanCar.info();
CarFactory sportFactory = SportCarFactory();
Car sportCar = sportFactory.createCar();
sportCar.info();
}
Будет напечатано:
This is a Sedan car This is a Sport car