DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Enabling Behavior-Driven Service Discovery: A Lightweight Approach to Augment Java Factory Design Pattern
  • Abstract Factory Pattern In Java
  • Java 8/9 Best Practices — Part-1 (Static Factory Methods)
  • How to Convert XLS to XLSX in Java

Trending

  • Stateless vs Stateful Stream Processing With Kafka Streams and Apache Flink
  • Issue and Present Verifiable Credentials With Spring Boot and Android
  • *You* Can Shape Trend Reports: Join DZone's Software Supply Chain Security Research
  • AI-Based Threat Detection in Cloud Security
  1. DZone
  2. Coding
  3. Java
  4. The Factory Pattern Using Lambda Expressions in Java 8

The Factory Pattern Using Lambda Expressions in Java 8

The factory pattern is one of the best known patterns in Java. If you're using lambda expressions, you can use those to implement the pattern, though beware scaling.

By 
Monika  Goel user avatar
Monika Goel
·
Mar. 01, 17 · Tutorial
Likes (57)
Comment
Save
Tweet
Share
88.6K Views

Join the DZone community and get the full member experience.

Join For Free

The factory pattern is one of the most used design patterns in Java. This type of design pattern falls under the host of creational patterns, as this pattern provides one of the best ways to create an object. The factory design pattern lets you create objects without exposing the instantiation logic to the client.

In this post, I would like to give an example of Factory pattern and then rewrite the same example using the lambda expression to be introduced in Java 8.

Factory Pattern: An Example

I am going to create a Shape interface as well as concrete classes implementing the Shape interface. A factory class ShapeFactory is defined as the next step.

Create an interface: Shape.java

public interface Shape {
   void draw();
}


Consider two implementations of this Shape interface: Circle.java & Rectangle.java

public class Rectangle implements Shape {

   @Override
   public void draw() {
      System.out.println("Inside Rectangle::draw() method.");
   }
}

public class Circle implements Shape {

   @Override
   public void draw() {
      System.out.println("Inside Circle::draw() method.");
   }
}


Create a Factory to generate an object of your concrete classes based on given information.

public class ShapeFactory {

   //use getShape method to get object of type shape 
   public Shape getShape(String shapeType){
      if(shapeType == null){
         return null;
      }
      if(shapeType.equalsIgnoreCase("CIRCLE")){
         return new Circle();

      } else if(shapeType.equalsIgnoreCase("RECTANGLE")){
         return new Rectangle();         
      }       
      return null;
   }
}


Use the Factory to get an object of concrete class by passing an information such as type: FactoryPatternDemo.java

public class FactoryPatternDemo {

   public static void main(String[] args) {
      ShapeFactory shapeFactory = new ShapeFactory();

      //get an object of Circle and call its draw method.
      Shape shape1 = shapeFactory.getShape("CIRCLE");

      //call draw method of Circle
      shape1.draw();

      //get an object of Rectangle and call its draw method.
      Shape shape2 = shapeFactory.getShape("RECTANGLE");

      //call draw method of Rectangle
      shape2.draw();
   }
}


Verify the output:

Inside Circle::draw() method.
Inside Rectangle::draw() method.


Factory Pattern: Refactor With Lambda Expressions

In Java 8, we can refer to constructors just like we refer to methods, by using
method references. For example, here’s how to refer to the Circle constructor:

Supplier<Shape> circleSupplier = Circle::new;
Circle circle = circleSupplier.get();


Using this technique, we could rewrite the previous code by creating a Map that maps a shape
name to its constructor:

final static Map<String, Supplier<Shape>> map = new HashMap<>();
  static {
    map.put("CIRCLE", Circle::new);
    map.put("RECTANGLE", Rectangle::new);
  }


We can now use this Map to instantiate different shapes, just as we did with the previous factory code:

public class ShapeFactory {

  final static Map<String, Supplier<Shape>> map = new HashMap<>();
  static {
    map.put("CIRCLE", Circle::new);
    map.put("RECTANGLE", Rectangle::new);
  }   
  public Shape getShape(String shapeType){
     Supplier<Shape> shape = map.get(shapeType.toUpperCase());
     if(shape != null) {
       return shape.get();
     }
     throw new IllegalArgumentException("No such shape " + shapeType.toUpperCase());
  }
}


Use the factory to get an object of concrete class using the lambda expression: FactoryPatternDemo.java

public class FactoryPatternDemo {

   public static void main(String[] args) {

     Supplier<ShapeFactory> shapeFactory =  ShapeFactory::new;

  //call draw method of circle
     shapeFactory.get().getShape("circle").draw();

     //call draw method of Rectangle
     shapeFactory.get().getShape("rectangle").draw();      
   }
}


Verify the output:

Inside Circle::draw() method.
Inside Rectangle::draw() method.


This is quite a neat way to make use of a Java 8 feature to achieve the same intent as the
factory pattern. But this technique doesn’t scale very well if the factory method getShape
needs to take multiple arguments to pass on to the Shape constructors! You’d have to provide
a different functional interface than a simple Supplier.

Factory (object-oriented programming) Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Enabling Behavior-Driven Service Discovery: A Lightweight Approach to Augment Java Factory Design Pattern
  • Abstract Factory Pattern In Java
  • Java 8/9 Best Practices — Part-1 (Static Factory Methods)
  • How to Convert XLS to XLSX in Java

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!