-
-
- Intent !--span class=" n Umber ">0
- applicability ! --span class= "number" >1
- structure !--span class= "number" >2
- !--span class= "number" >3
- effect !--span class= "number" >4
- reference !--span class= "number" >5
Intention
Dynamically add some additional responsibilities to an object.
Applicability
- Dynamically add responsibilities to a single object without affecting other objects
- Deal with the duties that can be revoked (?) Remove these features when certain features are not required)
- When the method of generating subclasses cannot be extended
Structure
Realize
Design Some drinks, these drinks can be selected by the customer to add a variety of seasonings.
First, the abstract class of drinks.
Abstract class Beverage{protected stringDescription ="Unknown Beverage";Public virtual string getdescription() {returnDescription; }Public abstract double cost() ; }
Next comes the specific beverage category
class Coffee:Beverage{Public Coffee() {Description ="Coffee"; } override public double cost() {return 1.99; } }
Then there is the abstract class of the adorner, which not only inherits the abstraction of the drink, but also contains a beverage member
Abstract class Condimentdecorator:Beverage{protectedBeverage beverage; override public abstract string getdescription() ; }
And finally, two concrete decorators.
class Milk:Condimentdecorator{Public Milk(beverage beverage) { This. Beverage = beverage; } override public string getdescription() {return "Milk"+ beverage.getdescription (); } override public double cost() {return.Ten+ Beverage.cost (); } }class Mocha:Condimentdecorator{Public Mocha(beverage beverage) { This. Beverage = beverage; } override public string getdescription() {return "Mocha"+ beverage.getdescription (); } override public double cost() {return. -+ Beverage.cost (); } }
Now, the customer is free to choose the seasoning.
class Program{ static void Main(string[] args) {Beverage Beverage =NewCoffee (); Console.WriteLine (beverage. GetDescription () +": $"+ Beverage. Cost ()); Beverage Mocha =NewMocha (beverage); Console.WriteLine (Mocha. GetDescription () +": $"+ Mocha. Cost ()); Beverage milk =NewMilk (beverage); Console.WriteLine (Milk. GetDescription () +": $"+ Milk. Cost ()); Beverage Mochamilk =NewMilk (Mocha); Console.WriteLine (mochamilk.getdescription () +": $"+ Mochamilk.cost ()); Console.readkey (); } }
Run results
Effect
1. More flexible than static inheritance
2. Avoid having too many features in a class at the top level of the hierarchy
3. The adorner is not the same as the object it decorates, and cannot be relied upon for object representation
4. Many small objects are produced
Reference
- "Head First design mode"
- "Design Mode"
Design Pattern C # implementation (12)--Decorative mode