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
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Enabling Behavior-Driven Service Discovery: A Lightweight Approach to Augment Java Factory Design Pattern
  • Zero-Downtime Deployments for Java Apps on Kubernetes
  • Rethinking Java CRUDs With Event Sourcing and CQRS Patterns
  • Detecting Bugs and Vulnerabilities in Java With SonarQube

Trending

  • RAG Is Not Enough: Advanced Retrieval Architectures Using Vertex AI Search on GCP
  • Edge Computing in Utility IoT: Two Architecture Patterns That Actually Work
  • Beyond Partitioning and Z-Order: A Deep Dive into Liquid Clustering for Unity Catalog Managed Tables
  • Catching Data Perimeter Drift Before It Reaches Production
  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
89.3K 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
  • Zero-Downtime Deployments for Java Apps on Kubernetes
  • Rethinking Java CRUDs With Event Sourcing and CQRS Patterns
  • Detecting Bugs and Vulnerabilities in Java With SonarQube

Partner Resources

×

Comments

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

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook