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 Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
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
  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.

Monika  Goel user avatar by
Monika Goel
·
Mar. 01, 17 · Tutorial
Like (57)
Save
Tweet
Share
83.80K 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.

Popular on DZone

  • Best Practices for Writing Clean and Maintainable Code
  • Connecting Your Devs' Work to the Business
  • Hackerman [Comic]
  • Core Machine Learning Metrics

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: