Temptations of Scala…

As I continue my romance with Scala language, I decided to take up the rubber duck code from Head First Design Patterns. The code already is implemented using Strategy pattern as we know. Just check the C# code juxtaposed against the Scala code, (dont ask which one is C# code)


class Program
{
static void Main(string[] args)
{
var actualDuck = new Duck(new ActualFlyBehavior(),
new ActualQuackBehavior());
actualDuck.DoFly();
actualDuck.DoQuack();
var rubberDuck = new Duck(new NoFlyBehavior(),
new NoQuackBehavior());
rubberDuck.DoFly();
rubberDuck.DoQuack();
Console.ReadLine();
}
}

public class ActualFlyBehavior : IFly
{
public void Fly()
{
Console.WriteLine("I am actually flying!!!");
}
}

public class ActualQuackBehavior : IQuack
{
public void Quack()
{
Console.WriteLine("I am actually quacking!!!");
}
}

public class NoFlyBehavior : IFly
{
public void Fly()
{
Console.WriteLine("---");
}
}

public class NoQuackBehavior : IQuack
{
public void Quack()
{
Console.WriteLine("---");
}
}

public class Duck
{
private readonly IFly fly;
private readonly IQuack quack;

public Duck(IFly fly, IQuack quack)
{
this.fly = fly;
this.quack = quack;
}

public void DoFly()
{
fly.Fly();
}

public void DoQuack()
{
quack.Quack();
}
}

public interface IFly
{
void Fly();
}

public interface IQuack
{
void Quack();
}
object Starter extends App
{
println("Hello World!!!")
val actualDuck = new ActualDuck
actualDuck.doFly()
actualDuck.doQuack()
val rubberDuck = new RubberDuck
rubberDuck.doFly()
rubberDuck.doQuack()
}

abstract class Duck
{
def doFly()
def doQuack()
}


class ActualDuck extends Duck with Fly with Quack
{

}

class RubberDuck extends Duck
{
def doFly() {println("---")}
def doQuack() {println("---")}
}

trait Fly
{
def doFly(){println("I am actually flying!!!")}
}

trait Quack
{
def doQuack(){println("I am actually quacking!!!")}
}
 
 
 
 
 

0 Comments:

Post a Comment