I am unaware of C# concept which is defined below.
I have following code below but i am unaware of what exactly is the use of last new DecoratorB( new DecoratorA(component))
in the Main function.
1) Can you please explain me what exactly the above code is doing and how references are set for a given object.
2) Also Display(string s, IComponent c)
accepts IComponent
as parameter so what exactly does the DecoratorA
and DecoratorB
class returns.
EDIT what exactly those nested constructor calls are doing in this example.
I tried debugging the code but no clue what exactly is happening.
static void Display(string s, IComponent c) {
Console.WriteLine(s+ c.Operation( ));
}
static void Main(){
IComponent component = new Component( );
Display("1. Basic component: ", component);
Display("2. A-decorated : ", new DecoratorA(component));
Display("3. B-decorated : ", new DecoratorB(component));
Display("4. B-A-decorated : ", new DecoratorB(
new DecoratorA(component)));
}
interface IComponent {
string Operation( );
}
class Component : IComponent {
public string Operation ( ) {
return "I am walking ";
}
}
class DecoratorA : IComponent {
IComponent component;
public DecoratorA (IComponent c) {
component = c;
}
public string Operation( ) {
string s = component.Operation( );
s += "and listening to Classic FM ";
return s;
}
}
class DecoratorB : IComponent {
IComponent component;
public string addedState = "past the Coffee Shop ";
public DecoratorB (IComponent c) {
component = c;
}
public string Operation ( ) {
string s = component.Operation ( );
s += "to school ";
return s;
}
public string AddedBehavior( ) {
return "and I bought a cappuccino ";
}
}
Also if i am missing a basic then please guide me to the required link
Thank you
EDIT 2
I want to know what kind of robustness is provided accessing the function using interface object. link here
//System.Console.WriteLine("Length: {0}", box1.getLength());
//System.Console.WriteLine("Width: {0}", box1.getWidth());
System.Console.WriteLine("Length: {0}", dimensions.getLength());
System.Console.WriteLine("Width: {0}", dimensions.getWidth());
static void Main()
{
// Declare a class instance box1:
Box box1 = new Box(30.0f, 20.0f);
// Declare an interface instance dimensions:
IDimensions dimensions = (IDimensions)box1;
// The following commented lines would produce compilation
// errors because they try to access an explicitly implemented
// interface member from a class instance:
//System.Console.WriteLine("Length: {0}", box1.getLength());
//System.Console.WriteLine("Width: {0}", box1.getWidth());
// Print out the dimensions of the box by calling the methods
// from an instance of the interface:
System.Console.WriteLine("Length: {0}", dimensions.getLength());
System.Console.WriteLine("Width: {0}", dimensions.getWidth());
}