[英]use java.util.function.Function to implement Factory Design Pattern
Is it correct to use java.util.function.Function to implement Factory Design Pattern 使用java.util.function.Function实现Factory Design Pattern是否正确
In the following example, I've used Function reference to instantiated a Person type object. 在下面的示例中,我使用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("Shan");
System.out.println(p.getName());
}
}
class Person{
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
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, eg a SmartPerson and a DumbPerson (implementing the same Person base class).
假设您有多种类型的人,例如SmartPerson和DumbPerson(实现相同的Person基类)。 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.
人们可以要求工厂创建一个聪明或愚蠢的人,而不知道实现差异,因为所有它返回的是一个Person对象。
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");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.