decorator pattern (tsz. decorator patterns)
A decorator minta (magyarul: dekorátor tervezési minta) egy strukturális design pattern, amely lehetővé teszi, hogy meglévő objektumokhoz dinamikusan új funkcionalitást adjunk hozzá, anélkül hogy megváltoztatnánk azok osztályát.
Ez egy alternatívája az öröklésnek, ha az osztály viselkedését szeretnénk bővíteni futásidőben.
A dekorátor minta:
+----------------+ | Component | <----- absztrakt interfész +----------------+ ^ | +---------------+ | ConcreteComp | <-- az alap implementáció +---------------+ ^ | +------------------+ +----------------+ | Decorator | <-----| ConcreteDecorX | +------------------+ +----------------+
#include <iostream>
#include <memory>
// Absztrakt interfész
class Coffee {
public:
virtual std::string getDescription() const = 0;
virtual double cost() const = 0;
virtual ~Coffee() {}
};
// Alap implementáció
class BasicCoffee : public Coffee {
public:
std::string getDescription() const override {
return "Basic coffee";
}
double cost() const override {
return 2.0;
}
};
// Dekorátor bázisosztály
class CoffeeDecorator : public Coffee {
protected:
std::unique_ptr<Coffee> coffee;
public:
CoffeeDecorator(std::unique_ptr<Coffee> c) : coffee(std::move(c)) {}
};
// Tej dekorátor
class Milk : public CoffeeDecorator {
public:
Milk(std::unique_ptr<Coffee> c) : CoffeeDecorator(std::move(c)) {}
std::string getDescription() const override {
return coffee->getDescription() + ", milk";
}
double cost() const override {
return coffee->cost() + 0.5;
}
};
// Cukor dekorátor
class Sugar : public CoffeeDecorator {
public:
Sugar(std::unique_ptr<Coffee> c) : CoffeeDecorator(std::move(c)) {}
std::string getDescription() const override {
return coffee->getDescription() + ", sugar";
}
double cost() const override {
return coffee->cost() + 0.2;
}
};
int main() {
std::unique_ptr<Coffee> c = std::make_unique<BasicCoffee>();
c = std::make_unique<Milk>(std::move(c));
c = std::make_unique<Sugar>(std::move(c));
std::cout << c->getDescription() << " costs $" << c->cost() << "\n";
}
Kimenet:
Basic coffee, milk, sugar costs $2.7
Minta | Kapcsolat |
---|---|
Composite | Több objektumot kezel egyként – gyakran együtt használják |
Strategy | Viselkedés megváltoztatása, de nem „rétegzett” módon |
Adapter | Más interface-t alakít – nem bővítés, hanem illesztés |
Proxy | Helyettesítés vagy vezérlés, nem bővítés céljából |