Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Java design patterns in Scala

Sponsored · SiteGround - Reliable hosting with speed, security, and support you can count on.

Java design patterns in Scala

Java patters in Scala, decorator, command, builder, iterator, strategy, null object

Avatar for Radim

Radim

June 23, 2014
Tweet

Other Decks in Programming

Transcript

  1. Java Collections.sort(people, new Comparator<Person>() { public int compare(Person p1, Person

    p2) { return p1.getFirstName().compareTo( ps.getFirstName()) } })
  2. Java public class PrintCommand implements Runnable { private final String

    s; PrintCommand(String s) { this.s = s; } public void run() { System.out.println(s); } } public class Invoker { private final List<Runnable> history = new ArrayList<>(); void invoke(Runnable command) { command.run(); history.add(command); } } Invoker invoker = new Invoker(); invoker.invoke( new PrintCommand( "Scala")); invoker.invoke( new PrintCommand( "Vienna"));
  3. Scala object Invoker { private var history: Seq[() => Unit]

    = Seq.empty def invoke(command: => Unit) { // by-name parameter command history :+= command _ } } Invoker.invoke(println( "foo"))
  4. Scala advanced def makePurchase(register: CaschRegister, amount: Int) = { ()

    = { println("Purchase in amount: " + amount) register.addCash(amount) } } // how to create purchase functions using closure
  5. Java Issues • constructor arguments Person(String n,String n2,String nick •

    Defaults (telescoping constructor problem) Person() Person(String name) Person(String name, String name2)...
  6. Java code public class ImmutablePerson { private final String firstName;

    public String getFirstName() { return firstName;} private ImmetablePerson(Builder builder) { firstName = builder.firstName; } public static Builder newBuilder() { return new Builder(); } } public static class Builder { private String firstName; public Builder withFirstName(String firstName) { this.firstName = firstName; return this; } public ImmutablePerson build () { return new ImmutablePerson(this); } }
  7. Scala - Case Class case class Person { firstName: String,

    LastName: String, nick: String = "") val p = Person(firstName = “Radim”, lastName = “Pavlicek”) val cloneMe = Person(firstName = “Radim”, lastName = “Pavlicek”) p.equals(cloneMe) // true val brother = p.copy(firstName = “Libor”) // Libor Pavlicek p.toString // Person[firstName=”Radim”, lastName= “Pavlicek”]
  8. Scala - Tuples • for explorative development def p =

    (“Radim”, “Pavlicek”) p._1 // Radim p._2 // Pavlicek
  9. Java public Set<Char> vowelsCount(String s) { Set<Char> l = new

    HashSet<Char>(); for (Char c : s.toLowerCase().toCharArray()) if (isVowel(c)) l.add(c) }
  10. Scala filter filtering certain elements from collection def vowelsNumber(word :

    String) = word.filter(isVowel).toSet vowelsNumber(“Radim”) // Set(‘a’, ‘i’)
  11. Scala map function is applied to each element def prependHello(names

    : Seq[String]) = names.map((name) => “Hello, “ + name)
  12. Scala reduce reduce sequence to a single value def sum(sq

    : Seq[Int]) = if (sq.isEmpty) 0 else sq.reduce((acc,curr) => acc + curr)
  13. Scala comprehensions • guard for (a <- list if isEven(a))

    • pattern matching for (Person(name, address) <- people) • still no mutable state
  14. Scala for comprehensions case class Person(name: String, addr: Address) case

    class Address(zip: Int) def greetings(people: Seq[Person]) = for (Person(name, address) <- people if isCloseZip(address.zip) ) yield “Hello, %s”.format(name)
  15. Template method defines the program skeleton of an algorithm in

    a method, called template method, which defers some steps to subclasses
  16. Java public abstract class Template { public void doStuff() {

    beforeStuff(); afterStuff(); } protected abstract void beforeStuff(); protected abstract void afterStuff(); }
  17. Scala Function Builder def doStuff( beforeStuff: () => Unit, afterStuff:

    () => Unit) = () = { beforeSuff() afterStuff() }
  18. Scala Function Builder def beforeStuff() = Console.println(“before”) def afterStuff() =

    Console.println(“after”) val test= doStuff(beforeStuff, afterStuff) scala> test
  19. Java public interface Strategy { int compute(int a, int b);

    } public class Add implements Strategy { public int compute(int a, int b) { return a + b; } } public class Multiply implements Strategy { public int compute(int a, int b) { return a * b; } } public class Context { private final Strategy strategy; public Context(Strategy strategy) { this.strategy = strategy; } public void use(int a, int b) { strategy.compute(a, b); } } new Context(new Multiply()).use( 2, 3);
  20. Scala define type alias and use first-class functions type Strategy

    = (Int, Int) => Int class Context(computer: Strategy) { def use(a: Int, b: Int) { computer(a, b) } } val add: Strategy = _ + _ val multiply: Strategy = _ * _ new Context(multiply).use( 2, 3)
  21. Null Object avoid null checks in code and centralize logic

    that deals with handling the absence of a value
  22. Java class NullPerson extends Person {....} public Person build(String first,

    String last) { if (first == null || last == null) return new NullPerson(); return new Person (first, last); }
  23. Scala val nullPerson = Person() // case class def build(first:

    Option[String], last: Option[String]) = (for (f <- first; l <- last) yield Person(f, l) ).getOrElse(nullPerson)
  24. Java public interface OutputStream { void write(byte b); void write(byte[]

    b); } public class FileOutputStream implements OutputStream { /* ... */ } public abstract class OutputStreamDecorator implements OutputStream { protected final OutputStream delegate; protected OutputStreamDecorator(OutputStream delegate) { this.delegate = delegate; } public void write(byte b) { delegate.write(b); } public void write(byte[] b) { delegate.write(b); } }
  25. Scala def add(a: Int, b: Int) = a + b

    def decorateLogger(calcF: (Int, Int) => Int) = (a: Int, b: Int) => { val result = calcF(a, b) println(“Result is: “ + result) // here it comes result }