Подробнее на 👉 refactoring.guru
#include <iostream>
// Интерфейс для реализации марки автомобиля
class CarMake {
public:
virtual void setMake() = 0;
};
// Конкретная реализация марки автомобиля
class Ford : public CarMake {
public:
void setMake() { std::cout << "Ford" << std::endl; }
};
class Toyota : public CarMake {
public:
void setMake() { std::cout << "Toyota" << std::endl; }
};
// Интерфейс для типа автомобиля
class CarType {
public:
virtual void setType() = 0;
};
// Конкретная реализация типа автомобиля
class Sedan : public CarType {
public:
void setType() { std::cout << "Sedan" << std::endl; }
};
class SportCar : public CarType {
public:
void setType() { std::cout << "Sportcar" << std::endl; }
};
// Абстрактный мост между маркой и типом автомобиля
class Car {
protected:
CarMake* make;
CarType* type;
public:
Car(CarMake* carMake, CarType* carType) : make(carMake), type(carType) {}
virtual void showDetails() = 0;
};
// Расширенная реализация моста
class LuxuryCar : public Car {
public:
LuxuryCar(CarMake* carMake, CarType* carType) : Car(carMake, carType) {}
void showDetails() {
make->setMake();
type->setType();
std::cout << "Luxury Car" << std::endl;
}
};
int main() {
CarMake* ford = new Ford();
CarMake* toyota = new Toyota();
CarType* sedan = new Sedan();
CarType* Sportcar = new SportCar();
Car* fordSedan = new LuxuryCar(ford, sedan);
Car* toyotaSportcar = new LuxuryCar(toyota, Sportcar);
fordSedan->showDetails();
toyotaSportcar->showDetails();
delete ford;
delete toyota;
delete sedan;
delete Sportcar;
delete fordSedan;
delete toyotaSportcar;
return 0;
}
Будет напечатано:
Ford Sedan Luxury Car Toyota SportCar Luxury Car
abstract class CarMake {
void setMake();
}
class Ford implements CarMake {
void setMake() {
print('Ford');
}
}
class Toyota implements CarMake {
void setMake() {
print('Toyota');
}
}
abstract class CarType {
void setType();
}
class Sedan implements CarType {
void setType() {
print('Sedan');
}
}
class SportCar implements CarType {
void setType() {
print('SportCar');
}
}
abstract class Car {
CarMake make;
CarType type;
Car(this.make, this.type);
void showDetails();
}
class LuxuryCar extends Car {
LuxuryCar(CarMake carMake, CarType carType) : super(carMake, carType);
void showDetails() {
make.setMake();
type.setType();
print('Luxury Car');
}
}
void main() {
CarMake ford = Ford();
CarMake toyota = Toyota();
CarType sedan = Sedan();
CarType sportcar = SportCar();
Car fordSedan = LuxuryCar(ford, sedan);
Car toyotaSportCar = LuxuryCar(toyota, sportcar);
fordSedan.showDetails();
toyotaSportCar.showDetails();
}
Будет напечатано:
Ford Sedan Luxury Car Toyota SportCar Luxury Car