Factory Design Pattern In Scala

Filed Under: Design Patterns

I’m going to deliver a series of Scala Design Patterns in my coming posts. I will pick-up each Java Design Pattern Tutorial explained in JournalDEV and convert it into Scala.

We will also discuss about which Language is best: Java Vs Scala to implement them. In this post, we are going to discuss about Factory Design Pattern implementation in Scala Language.

Before reading this post, please go through Java version of Factory Design Pattern.

POST Brief Table Of Content

  • Factory Design Pattern
  • Advantages of Factory Design Pattern
  • Factory Design Pattern in Scala
  • Improved Factory Design Pattern in Scala
  • Factory Design Pattern: Java Vs Scala

Factory Design Pattern

Factory Design Pattern is one of the popular Creational Design Patterns.

The main aim of Factory Design Pattern is that separate objects or instances creation logic from client. We implement Object creation logic in a Factory class without exposing that logic to the client.

Factory Design Pattern is also know as Factory Method Design Pattern. It is used when we have a super class with multiple sub-classes and based on input, we need to return one of the sub-class.

Advantages of Factory Design Pattern

Factory Design Pattern have the following benefits:

  • Loose Coupling between Object Creation logic and Client.
  • Clear separation of Responsibilities.
  • Easy to change object creation logic without effecting Client program.

Factory Design Pattern in Scala

In this section, we will take existing “Factory Design Pattern” implemented in Java Language and convert into Scala Language. We will refine this example in next section.

In Scala, We can implement Factory class using Singleton Object and Pattern Matching. If you are not sure what is Singleton Object, how to implement it in Scala and Pattern Matching, please go through my Scala Tutorial.

First develop our class hierarchy and Factory class as show below:

ComputerFactory.scala


package com.journaldev.designpattern.factory

trait Computer{
  def getRAM():String
  def getHDD():String
  def getCPU():String

  override def toString = "RAM= " + getRAM +", HDD=" + getHDD + ", CPU=" + getCPU
}

private class PC(val ram:String, val hdd:String, val cpu:String) extends Computer{
  def getRAM():String =  ram
  def getHDD():String = hdd
  def getCPU():String = cpu
}

private class Server(val ram:String, val hdd:String, val cpu:String) extends Computer{
  def getRAM():String =  ram
  def getHDD():String = hdd
  def getCPU():String = cpu
}

object ComputerFactory{
  def apply(compType:String, ram:String, hdd:String, cpu:String) = compType.toUpperCase match {
        case "PC" => new PC(ram,hdd,cpu)
        case "SERVER" => new Server(ram,hdd,cpu)
      }
}

Scala does not have interface concept. However, it has more powerful concept than interface that is: Trait. We have developed a based trait with all our required functions or methods.

Here ‘ComputerFactory’ object is a Singleton Object. It is used to provide factory method to create our objects. Next develop a client to test this Scala program.

FactoryMethodDesignPatternClient.scala


object FactoryMethodDesignPatternClient extends App{
  val pc = ComputerFactory("pc","2 GB","500 GB","2.4 GHz");
  val server = ComputerFactory("server","16 GB","1 TB","2.9 GHz");

  println("Factory PC Config::"+pc);
  println("Factory Server Config::"+server);
}

output


Factory PC Config::RAM= 2 GB, HDD=500 GB, CPU=2.4 GHz
Factory Server Config::RAM= 16 GB, HDD=1 TB, CPU=2.9 GHz

Improved Factory Design Pattern in Scala

In this section, we are going to improved our previous example by using Scala case classes. If you are new to Case Classes, please read my “Scala Case Classes In Depth” post in my Scala Tutorial.


package com.journaldev.designpattern.factory

trait Computer{
  def ram:String
  def hdd:String
  def cpu:String

  override def toString = "RAM= " + ram +", HDD=" + hdd + ", CPU=" + cpu
}

private case class PC(ram:String, hdd:String, cpu:String) extends Computer

private case class Server(ram:String, hdd:String, cpu:String) extends Computer

object ComputerFactory{
  def apply(compType:String, ram:String, hdd:String, cpu:String) = compType.toUpperCase match {
    case "PC" => PC(ram,hdd,cpu)
    case "SERVER" => Server(ram,hdd,cpu)
  }
}

Use same client to test this program, we will get same output.

Factory Design Pattern: Java Vs Scala

If we observe both Java and Scala Factory Design Pattern examples, we can observe that Scala is the best language to implement this design pattern. The reason is:

  • Very concise or less code
  • No boilerplate code
  • Very expression code

That’s it all about “Factory Design Pattern In Scala”. We will discuss some more Design Patterns In Scala Language in my coming posts.

Please drop me a comment if you like my post or have any issues/suggestions.

Comments

  1. Rahul says:

    When I tried to implement this using the case class getting error like the class PC and server needs to be abstract because it has 3 unimplemented methods.

  2. Maheswari Ganesh says:

    Really a great post. I loved it.. Thank yo for attaining this design pattern which makes me to assure the knowledge.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages