Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda implementing Interface

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

From the book: enter image description here

// 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#?

like image 552
BobSwanson Avatar asked Apr 17 '16 20:04

BobSwanson


1 Answers

This does not work because in C#, lambda expressions map to delegates - a concept that does not exist in Java. Java has had a lot of these one-method interfaces for a long time before they finally introduced lambdas in Java 8. Given this and the lack of delegates, it was more or less natural to associate lambdas wit these one-method interfaces. C# / .NET, on the other hand, had delegates from the beginning and used them at many places where you would find a one-method interface in Java. Compare e.g. Observer and EventHandler.

So in a .NET API, you would consider using a delegate type like Action instead of ICommand, and then you would be able to use a lambda with it.

It should also be noted that .NET does have one-method interfaces, too. Some basic guidance about when to choose an interface or a delegate can be found at MSDN.

like image 121
Matthias Avatar answered Oct 24 '22 09:10

Matthias