加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 01:07:11 所属栏目:Java 来源:网络整理
导读:使用java.util.function.Function实现Factory Design Pattern是否正确 在下面的示例中,我使用Function引用来实例化Person类型对象. import java.util.function.Function;public class Main { public static void main(String[] args) { Function 最佳答案 工

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

在下面的示例中,我使用Function引用来实例化Person类型对象.

import java.util.function.Function;

public class Main {
    public static void main(String[] args) {
        Function
最佳答案
工厂设计模式用于隐藏对象工厂背后的实现逻辑,其功能是使用继承来实现此目的.假设您有多种类型的人,例如一个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");
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读