In the book I'm reading "Head First Design Patterns", Command Pattern there is an example where they're substituting an Interface with Lambda.
Is this something that only Java is capable of? Here is an example
// Receiver
public class Light
{
public void On() {
Console.WriteLine("Lights on");
}
public void Off() {
Console.WriteLine("Ligts off");
}
}
// Command interface
public interface ICommand
{
void Execute();
}
// Concrete command
public class SimpleCommandLightOn : ICommand
{
private readonly Light light;
public SimpleCommandLightOn(Light light) {
this.light = light;
}
public void Execute() {
light.On();
}
}
// Concrete command
public class SimpleCommandLightOff : ICommand
{
private readonly Light light;
public SimpleCommandLightOff(Light light)
{
this.light = light;
}
public void Execute()
{
light.Off();
}
}
// Invoker
public class SimpleRemoteControl
{
private ICommand command;
public void SetCommand(ICommand command) {
this.command = command;
}
public void OnButtonPress() {
command.Execute();
}
// OffCommand needs to be set
public void OffButtonPress() {
command.Execute();
}
}
In the book they're stating that this is possible:
Light light = new Light();
remote.SetCommand(() => light.On());
However c# throws an error. Is this no the case when working with C#?
Aucun commentaire:
Enregistrer un commentaire