This book uses the example of starbazgarfi.
When the user needs houseblend plus seasoning steamed milk, soy milk, Moka, and other spices.
At this time, it is impossible to add a seasoning to each houseblend to become an object. If so
This is troublesome. When there are 10 kinds of main materials and 10 kinds of spices, there are 100 objects.
It is certainly impossible to add 10 more objects to one type of primary material.
So what we do is
Create 10 main material objects, and then create 10 seasoning objects to decorate the super objects of 10 main material objects,
In this way, you can create up to 11 objects when you need a cup of ingredients and spices. If you follow the above steps, although 11 objects are also created, each object contains a lot of redundant code, and once you want to modify it, it will be troublesome.
The decoration mode is simplified.
The above is feelings. The following is the code that really needs to be viewed.
It is estimated that I will understand my feelings after reading the code.
Using system;
Using system. Collections. Generic;
Using system. text;
Using system. IO;
Namespace decorator
{
Class Program
{
Static void main (string [] ARGs)
{
/// Test
Beverage beverage = new espresso ();
System. Console. writeline (beverage. getdescription () + "$" + beverage. Cost ());
Beverage beverage3 = new houseblend ();
Beverage3 = new mocha (beverage3 );
Beverage3 = new mocha (beverage3 );
System. Console. writeline (beverage3.getdescription () + "$" + beverage3.cost ());
}
}
/// <Summary>
/// Decoration
/// </Summary>
Public abstract class Beverage
{
Public String strdescription = "unknow beverage ";
Public Virtual string getdescription ()
{
Return strdescription;
}
Public abstract double cost ();
}
/// <Summary>
/// Extension class
/// </Summary>
Public abstract class condimentdecorator: Beverage
{
Public override string getdescription ()
{
Return strdescription;
}
}
/// <Summary>
/// Main material type
/// </Summary>
Public class espresso: Beverage
{
Public espresso ()
{
Strdescription = "Espresso ";
}
Public override double cost ()
{
Return 1.99;
}
}
/// <Summary>
/// Main material type
/// </Summary>
Public class houseblend: Beverage
{
Public houseblend ()
{
Strdescription = "house blend coffee ";
}
Public override double cost ()
{
Return 0.89;
}
}
/// <Summary>
/// Decoration
/// </Summary>
Public class mocha: condimentdecorator
{
Beverage beverage;
Public mocha (beverage)
{
This. Beverage = beverage;
}
Public override string getdescription ()
{
Return beverage. getdescription () + ", Monia ";
}
Public override double cost ()
{
Return 0.20 + beverage. Cost ();
}
}
}