Decorator Pattern explicat in PHP

Stefanescu Mihai 9 months ago Design Patterns

Decorator pattern permite utilizatorului sa adauge functionalitate noua unui obiect deja existent fara sa il modifice. Acesta este un design pattern structural.

Implementare
Vom demonstra implementarea lui folosinde de un exemplu cat se poate de simplu. Presupunand ca facem un site pentru un restaurant si vrem sa calculam pretul pornind de la o pizza de baza + un pret anume pentru fiecare topping.
Intradevar, am putea avea o clasa cu mai multe metode care sa tot adauge valori pe pret, ceva de genul asta, doar acest gen de cod ar ajunge foarte incurcat intr-un timp foarte scurt:

class Pizza {
    public $cost = 15;

    public function getCost() {
        return $this->cost;
    }

    public function addCheese() {
        $this->cost += 5;
    }

    public function addMushrooms() {
        $this->cost += 4;
    }

    public function addBacon() {
        $this->cost += 7;
    }    
}

Putem observa din start problema cu acest gen de clasa, pe masura ce avem din ce in ce mai multe topping-uri o sa avem din ce in ce mai multe metode.

In schimb, hai sa facem o clasa cat se poate de simpla numita BasePizza care sa implementeze interfata PizzaInterface care te oblica sa ai metoda getCost, care sa intoarca costul doar pentru o pizza de baza:

interface PizzaInterface {
    public function getCost();
}

class BasePizza implements PizzaInterface {
    public function getCost()
    {
        return 15;
    }
}

Acum, pentru fiecare topping pe care il avem mai cream cate o clasa specifica care sa implementeze interfata definita mai sus (PizzaInterface) si primeste ca parametru in constructor o interfata de tip PizzaInterface astfel:

class CheeseTopping implements PizzaInterface {
    /** PizzaInterface */
    private $pizza;

    public function __construct(PizzaInterface $pizza)
    {
        $this->pizza = $pizza;
    }

    public function getCost()
    {
        return 5 + $this->pizza->getCost();
    }
}

class BaconTopping implements PizzaInterface {
    /** PizzaInterface */
    private $pizza;

    public function __construct(PizzaInterface $pizza)
    {
        $this->pizza = $pizza;
    }

    public function getCost()
    {
        return 7 + $this->pizza->getCost();
    }
}

Acum hai sa vedem ce am facut pana acum. Presupunand ca vreau o pizza de baza pot rula

$basePizza = new BasePizza;
echo $basePizza->getCost(); // rezultatul va fi 15 (cel din clasa BasePizza)

Apoi, sa zicem ca vreau un topping, voi avea codul:

$basePizza = new BasePizza;

$cheesePizza = new CheeseTopping($basePizza);
echo $cheesePizza->getCost();// unde rezultatul va fi 20 (BasePizza 15 + CheeseTopping 5)

Ba chiar mai mult, pot merge asa cat de departe vreau, adaugand "extra" functionalitate unei clase deja existente fara sa o modific:

$basePizza = new BasePizza;

$cheesePizza = new CheeseTopping($basePizza);
$baconTopping = new BaconTopping($cheesePizza);

echo $baconTopping->getCost();

 

Programator de ~8 ani, am lucrat la proiecte din mai multe industrstrii, de la eCommerce la telecomunicatii la automatizari. In acest timp am folosi diferite tehnologii, de la PHP, MySQL, PostgreSql, RabbitMq, Redis, Memcached si altele.


Get in touch
Pentru nelamuriri, dubii, comentarii si chestii de pe suflet ne putem auzi pe Discord, Reddit sau poti deschide o discutie noua pe forum

Essie # 4 weeks ago Excellent way of describing, and nice piece of writing to get information about my presentation subject, which i am going to convey in institution of higher education.
Aleida # 3 weeks ago This is the right webpage for anyone who would like to understand this topic. You understand a whole lot its almost tough to argue with you (not that I really would want to…HaHa). You definitely put a brand new spin on a topic which has been discussed for decades. Great stuff, just wonderful!
Medikamente ohne Rezept legal in Belgien kaufen # 3 weeks ago It's not my first time to pay a visit this web site, i am visiting this web page dailly and take good facts from here every day.
Jaimie # 3 weeks ago I constantly emailed this weblog post page to all my contacts, for the reason that if like to read it next my friends will too.
Eric # 3 weeks ago whoah this blog is wonderful i really like reading your posts. Keep up the great work! You recognize, many people are hunting around for this information, you could aid them greatly.
Jasmine # 2 weeks ago It's an awesome paragraph in favor of all the internet viewers; they will take advantage from it I am sure.
xetin disponible en pharmacie suisse en ligne # 2 weeks ago Right away I am ready to do my breakfast, once having my breakfast coming over again to read other news.
Puedo comprar albuterol sin receta en Lima # 2 weeks ago Very rapidly this website will be famous among all blogging and site-building visitors, due to it's fastidious articles
kein Rezept erforderlich # 1 week ago Hey there! I know this is kinda off topic nevertheless I'd figured I'd ask. Would you be interested in trading links or maybe guest writing a blog article or vice-versa? My blog covers a lot of the same topics as yours and I believe we could greatly benefit from each other. If you're interested feel free to shoot me an email. I look forward to hearing from you! Superb blog by the way!
anafranil in niederländischer Apotheke erhältlich # 6 days ago Hello to every , since I am genuinely eager of reading this weblog's post to be updated regularly. It carries fastidious stuff.
noritacin sin receta en La Paz # 5 days ago Thanks for finally talking about >Decorator Pattern explicat in PHP - Invata-Programare <Loved it!
Sergio # 3 days ago Very nice post. I just stumbled upon your blog and wanted to say that I've truly enjoyed surfing around your blog posts. In any case I'll be subscribing to your rss feed and I hope you write again very soon!
ramipril en venta libre en Argentina # 2 days ago Highly descriptive post, I liked that a lot. Will there be a part 2?
chloromycetin vrij verkrijgbaar in Luik # 7 hours ago Wow, that's what I was searching for, what a stuff! present here at this website, thanks admin of this site.
Club-ul este dedicat membrilor si ofera access la mai multe zone ale website-ului.
Login Register

🔖 Bookmarks
✨ Pentru a sustine aceasta comunitate am sa te rog sa te autentifici sau sa te inregistrezi!

🌪️ Discord
Back to top
Folosim cookie-uri pentru a oferi functionalitatile critice ale aplicatiei Invata-Programare. Folosim cookie-uri si pentru a analiza traficul, pentru care e nevoie de consimtamantul dvs. explicit.