jeudi 3 décembre 2015

Decorator Pattern from Head First Book

I am working on a excursive from book Head First Design Patterns . Problem: Use Decorator pattern on starbuzz application to add size to this existing code

Beverage.Class

package CoffeHouse.drinks;

import CoffeHouse.drinks.sizedBevrage.Size;

/**
 * trying to implement decorator pattern and understand why and how it is implemented
 * @author praveen
 *
 */
public abstract class Bevrage {
        
        Size drinkSize = null;
        
        String description = "Unknown Drink";
        
        public String getDescription(){
                return description;
        }
        
        public Size getSize(){
                return drinkSize;
        }
        
        public abstract double cost();
        
}

Expresso Class

public class Expresso extends Bevrage {
        
        public Expresso(){
                this.description = "Expresso";
        }
        
        @Override
        public double cost() {
                // TODO Auto-generated method stub
                return 1.19;
        }

}

Condiment class

package CoffeHouse.condiments;

import CoffeHouse.drinks.Bevrage;

public abstract class CondimentDecorator extends Bevrage{
        public abstract String getDescription();
}

Mocha Class

package CoffeHouse.condiments;

import CoffeHouse.drinks.Bevrage;

public class Mocha extends CondimentDecorator{
        
        private Bevrage bevrage;
        
        public Mocha(Bevrage be){
                this.bevrage  = be;
        }
        @Override
        public String getDescription() {
                // TODO Auto-generated method stub
                return this.bevrage.getDescription()+",Mocha";
        }

        @Override
        public double cost() {
                // TODO Auto-generated method stub
                return this.bevrage.cost()+0.15;
        }

}

We are asked to edit this code so as to add size of the drink and determine the cost of condiments based on size. The issue I have is if I add size methods to beverage abstract class the mocha class also inherits it . I don't want to give mocha class the ability to change size of drink . Is this limitation of decorator pattern or is there a workaround it

Aucun commentaire:

Enregistrer un commentaire