Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use java.util.function.Function to implement Factory Design Pattern

Is it correct to use java.util.function.Function to implement Factory Design Pattern

In the following example, I've used Function reference to instantiated a Person type object.

import java.util.function.Function;

public class Main {
    public static void main(String[] args) {
        Function<String , Person> myFunc = (String s) -> new Person(s);
        Person p = myFunc.apply("John");
        System.out.println(p.getName());
    }
}

class Person{
    private String name;

    public Person(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }  
}
like image 679
shanwije Avatar asked Oct 17 '22 18:10

shanwije


1 Answers

The factory design pattern is used to hide implementation logic behind an object factory and its power is to use inheritance to achieve this. Say you would have more than one type of person, e.g. a SmartPerson and a DumbPerson (implementing the same Person base class). One could ask the factory to create either a smart or a dumb person without ever knowing about the implementation differences, since all it ever returns is a Person object.

You can instantiate a person with a function referring to the constructor, but this pattern is about the location of the object creation, allowing you to hide certain implementation logic.

This hiding of logic behind a factory saves you a lot of time in the future where different classes may use the factory to create persons, because a change to the way you create a person would only require you to modify the creation methods in the factory and does not affect each individual class using the factory.

@Test
public void testSimpleFactory() {
    PersonFactory personFactory = new PersonFactory();
    Person person = personFactory.createPerson("dumb");
    person.doMath(); // prints 1 + 1 = 3
}


public class PersonFactory {

    public Person createPerson(String characteristic) {
        switch (characteristic) {
            case "smart":
                return new SmartPerson();
            case "dumb":
                return new DumbPerson();
            default:
                return null;
        }
    }
}

public interface Person {
    void doMath();
}

public class SmartPerson implements Person {
    @Override
    public void doMath() {
        System.out.println("1 + 1 = 2");
    }
}

public class DumbPerson implements Person {
    @Override
    public void doMath() {
        System.out.println("1 + 1 = 3");
    }
}
like image 70
Luciano van der Veekens Avatar answered Oct 21 '22 05:10

Luciano van der Veekens