Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Problems
  • Python
  • C
  • C++
  • Java
  • Courses
  • Machine Learning
  • DevOps
  • Web Development
  • System Design
  • Aptitude
  • Projects
Open In App
Next Article:
Using Extractors with Pattern Matching In Scala
Next article icon

The Factory Pattern in Scala

Last Updated : 22 Jan, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report

The factory method is used to offer a single interface to instantiate one of the multiple classes. In the Factory pattern, the objective is to make the object in such a way that it does not expose to the creation logic to the Client and can always refer to a newly created object with the help of a common interface.

Let’s try to understand it with an example.

Assume that we need to create a library for a Car Purchase Application. The library is supposed to give three choices of cars types.

  1. Standard
  2. Deluxe
  3. Luxury

We are following an object-oriented design, and hence we decided to create three different classes. One for each car type. We also want to provide methods to get the booking price, Brands, and availability. All three classes will implement their methods individually but we have to decide on a simple method to create a Car object. So that all the cars can be purchased using the same method. Here is an example of how we want to book a car. the first statement returns an instance of a Standard car. the second statement returns a Deluxe Car, and the third one gives a Luxury Car. we are in this case offering one single method to create a variety of objects. the method Car here is a factory of Cars. we can book whatever type of car we need and as many as we want. this type of object creation makes programming very easy and the codes compact. one need not worry about different classes for different kinds of cars. That’s what a factory method is all about.




// Scala program of Design factory pattern
  
// creating abstract class for the car
abstract class Car{
          
        // Creating four abstract methods
        def bookingPrice : Double
        def Brands : List[String]
        def availability : Int
        def book(noOfCars:Int)
    }
  
    // Creating an object
    object Car{
        val STANDARD = 0
        val DELUXE = 1
        val LUXURY = 2
  
        // Creating private class
        private class standardCar extends Car{
            private var _availability = 100
            override def bookingPrice = 200000
            override def Brands = List("Maruti", "Tata", "Hyundai")
            override def availability = _availability
            override def book(noOfCars:Int) = {
                _availability = _availability - noOfCars
            }
        }
  
        // Creating private class
        private class DeluxeCar extends Car{
            private var _availability = 50
            override def bookingPrice = 500000
            override def Brands = List("Honda", "Mahindra", "Chevrolet")
            override def availability = _availability
            override def book(noOfCars:Int) = {
                _availability = _availability - noOfCars
            }
        }
  
        // Creating private class
        private class LuxuryCar extends Car{
            private var _availability = 5
            override def bookingPrice = 900000
            override def Brands = List("Audi","BMW", "Mercedes")
            override def availability = _availability
            override def book(noOfCars:Int) = {
                _availability = _availability - noOfCars
            }
        }
          
        // create the apply method
        // single method to create a variety of objects
        def apply(carType:Int):Car = {
            carType match {
                case LUXURY => new LuxuryCar()
                case DELUXE => new DeluxeCar()
                case STANDARD => new standardCar()
                case _ => new standardCar()
            }
        }
         // Main method 
        def main(args: Array[String])  
        { 
            val s = Car(STANDARD)   
            println(s.bookingPrice)
            println(s.availability) 
        }        
    }
 
 

Output:

200000.0  100  

The factory method thus helps a lot in making programming concepts easier. In this way, we can always save the codespace and the number of classes if declaring multiple objects of same type with some dissimilarities.



Next Article
Using Extractors with Pattern Matching In Scala

S

ShikharMathur1
Improve
Article Tags :
  • Scala
  • Scala
  • Scala-OOPS

Similar Reads

  • Scala | Pattern Matching
    Pattern matching is a way of checking the given sequence of tokens for the presence of the specific pattern. It is the most widely used feature in Scala. It is a technique for checking a value against a pattern. It is similar to the switch statement of Java and C. Here, "match" keyword is used inste
    3 min read
  • Using Extractors with Pattern Matching In Scala
    Scala Extractor is defined as an object which has a method named unapply as one of its part. Extractors can be utilized in Pattern Matching. The unapply method will be executed spontaneously, While comparing the Object of an Extractor in Pattern Matching. Below is the example of Extractor with patte
    2 min read
  • Pure Function In Scala
    In any programming language, there are two types of functions: 1. PURE FUNCTIONS 2. IMPURE FUNCTIONSThere is a basic difference between the two, that is pure function doesn’t change the variable it’s passed and an impure function does. For example, there exists a function which increases the input b
    3 min read
  • Interesting fact about Scala
    Scala(pronounced as "skah-lah") is general-purpose programming language designed by Martin Odersky. The design of Scala started in 2001 at EPFL, Lausanne, Switzerland. Scala was released publicly in 2004 on Java platform. Scala is designed to be concise and addresses criticisms of Java. Scala source
    3 min read
  • Scala Parser Combinators
    When a parser generator is required, some famous parsers that cross our mind are: Yacc and Bison for parsers written in C and ANTLR for parsers written in Java but they are designed to run for specific programming languages. This shortens the scope of use of parsers. However, Scala provides a unique
    3 min read
  • Scala List +() operator with example
    The +() operator in Scala is utilized to append an element to the list. Method Definition: def +(elem: A): List[A] Return Type: It returns a list of the stated elements after appending it to an another element. Example #1: // Scala program of +() // method // Creating object object GfG { // Main met
    1 min read
  • Scala List :::() operator with example
    The :::() operator in Scala is utilized to join the List in the argument to the another List. Method Definition: def :::(prefix: List[A]): List[A] Return Type: It returns a list after joining one list to the another one. Example #1: // Scala program of :::() // method // Creating object object GfG {
    1 min read
  • Operators in Scala
    An operator is a symbol that represents an operation to be performed with one or more operand. Operators are the foundation of any programming language. Operators allow us to perform different kinds of operations on operands. There are different types of operators used in Scala as follows: Arithmeti
    11 min read
  • Scala List ::() operator with example
    The ::() operator in Scala is utilized to add an element to the beginning of the List. Method Definition: def ::(x: A): List[A] Return Type: It returns the stated list after adding an element to the beginning of it. Example #1: // Scala program of ::() // method // Creating object object GfG { // Ma
    1 min read
  • Recursive Streams and collection in Scala
    Recursive forms have their definition in terms of themselves like we have subfolders in folders which can further have subfolders. Recursive methods calling themselves is also a recursive form. Similar forms can be used to create a recursive stream. Example 1: Creating a lazy list C/C++ Code // Scal
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences