使用java.util.function.function来实现Factory Design Pattern



使用java.util.function.function实现Factory Design Pattern 是否正确

在下面的示例中,我使用Function引用实例化了一个Person类型的对象。

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;
}  
}

工厂设计模式用于隐藏对象工厂背后的实现逻辑,其功能是使用继承来实现这一点。假设你有不止一种类型的人,例如SmartPerson和DumbPerson(实现相同的person基类)。可以要求工厂在不知道实现差异的情况下创建一个聪明或愚蠢的人,因为它只返回一个person对象。

您可以用引用构造函数的函数实例化一个人,但这种模式是关于对象创建的位置,允许您隐藏某些实现逻辑。

这种将逻辑隐藏在工厂后面的做法为您节省了大量时间,将来不同的类可能会使用工厂来创建人员,因为更改创建人员的方式只需要修改工厂中的创建方法,而不会影响使用工厂的每个单独的类。

@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");
}
}

最新更新