java - Why do we need the decorator in the decorator design pattern? -


presuming have class named a, , want use decorator design pattern. correct me if i'm wrong, work , we'll need create decorator class, adecorator, hold reference a instance, , other decorators extend add functionality.

i don't understand why have create decorator class, instead of using a instance?

the decorator pattern used add capabilities objects dynamically (that is, @ run time). object have capabilities fixed when write class. important point functionality of object extended in way transparent client of object because implements same interface original object delegates responsibility decorated object.

the decorator pattern works in scenarios there many optional functionality object may have. without decorator pattern have create different class each object-option configuration. 1 example pretty useful comes head first design patterns book o'reilly. uses coffee shop example sounds starbucks.

so have basic coffee method cost.

public double cost(){      return 3.45; } 

then customer can add cream costs 0.35 create coffeecream class cost method:

public double cost(){     return 3.80; } 

then customer may want mocha costs 0.5, , may want mocha cream or mocha without cream. create classes coffeemochacream , coffeemocha. customer wants double cream create class coffeecreamcream… etc. end class explosion. please excuse poor example used. it's bit late , know it's trivial express point.

instead can create item abstract class abstract cost method:

public abstract class item{     public abstract double cost(); } 

and can create concrete coffee class extends item:

public class coffee extends item{     public double cost(){        return 3.45;     } } 

then create coffeedecorator extend same interface , contain item.

public abstract class coffeedecorator extends item{      private item item;      ... } 

then can create concrete decorators each option:

public class mocha extends coffeedecorator{     public double cost(){      return item.cost() + 0.5;    }  } 

notice how decorator not care type of object wrapping long it's item? uses cost() of item object , adds own cost.

public class cream extends coffeedecorator{     public double cost(){      return item.cost() + 0.35;    }  } 

now possible large number of configurations these few classes: e.g.

 item drink = new cream(new mocha(new coffee))); //mocha cream 

or

 item drink = new cream(new mocha(new cream(new coffee))));//mocha double cream 

and on.


Comments

Popular posts from this blog

windows - Why does Vista not allow creation of shortcuts to "Programs" on a NonAdmin account? Not supposed to install apps from NonAdmin account? -

c++ - How do I get a multi line tooltip in MFC -

unit testing - How to mock PreferenceManager in Android? -