Java工厂设计模式或工厂类的解释。

huangapple go评论73阅读模式
英文:

Explanation of Java Factory Design Pattern or Factory Class

问题

以下是翻译好的内容:

我正在浏览 HackerRank,关于工厂设计模式或工厂类,我有一个快速的问题。我正在完成一个基本挑战(https://www.hackerrank.com/challenges/java-factory/problem),并且已经解决了它(代码如下所示)。我编写了由下面的注释指示的代码部分,其余部分是提供的。

import java.util.*;
import java.security.*;

interface Food {
    public String getType();
}

class Pizza implements Food {
    public String getType() {
        return "有人点了快餐!";
    }
}

// 我从这里开始实现
class Cake implements Food {
    public String getType() {
        return "有人点了甜点!";
    }
}

class FoodFactory {
    public Food getFood(String order) {
        if (order.equalsIgnoreCase("Pizza")) {
            return new Pizza();
        } else {
            return new Cake();
        }
    }
}
// 我实现的部分到这里结束

public class Solution {
    public static void main(String args[]) {
        Do_Not_Terminate.forbidExit();

        try {
            Scanner sc = new Scanner(System.in);
            // 创建工厂
            FoodFactory foodFactory = new FoodFactory();

            // 工厂实例化对象
            Food food = foodFactory.getFood(sc.nextLine());

            System.out.println("工厂返回了 " + food.getClass());
            System.out.println(food.getType());
        } catch (Do_Not_Terminate.ExitTrappedException e) {
            System.out.println("终止失败!");
        }
    }
}

我花了相当多的时间阅读了几个工厂设计模式的在线示例,但是我不太清楚工厂模式的目的是什么,以及为什么它有益,或者它在简化什么问题/解决了什么问题。同样,尝试这个实际的例子也没有很好地解释问题。

有人能以非常基本的方式解释一下吗?同样,有没有使用工厂模式的替代方案?也许这个练习中提供的代码过于简化了问题,这就是为什么我对工厂模式的成就不太清楚。谢谢提供帮助,一些实际的例子会非常有帮助。我已经阅读了关于各种设计模式的资料,知道它们是什么,但由于在实际应用中的经验有限,我对问题理解不够深入。

英文:

I am going through HackerRank and had a quick question regarding the Factory Design Pattern or Factory Class. I am going through a basic challenge (https://www.hackerrank.com/challenges/java-factory/problem) and was able to solve it (code shown below). I wrote the portion of the code that is indicated by the comments below, while the rest was provided.

import java.util.*;
import java.security.*;
interface Food {
public String getType();
}
class Pizza implements Food {
public String getType() {
return "Someone ordered a Fast Food!";
}
}
//I implemented the part starting here    
class Cake implements Food {
public String getType() {
return "Someone ordered a Dessert!";
}
}
class FoodFactory {
public Food getFood(String order) {
if (order.equalsIgnoreCase("Pizza")){
return new Pizza();}
else return new Cake();
}//End of getFood method; this is the end of the part I implemented
}//End of factory class
public class Solution {
public static void main(String args[]){
Do_Not_Terminate.forbidExit();
try{
Scanner sc=new Scanner(System.in);
//creating the factory
FoodFactory foodFactory = new FoodFactory();
//factory instantiates an object
Food food = foodFactory.getFood(sc.nextLine());
System.out.println("The factory returned "+food.getClass());
System.out.println(food.getType());
}
catch (Do_Not_Terminate.ExitTrappedException e) {
System.out.println("Unsuccessful Termination!!");
}
}
}

I have spent quite a bit of time reading through several examples online of the Factory Design Pattern, but it isn't exactly clear to me what is the purpose of the Factory Pattern and why it is beneficial or what it is simplifying/what problem it is solving. Similarly, trying this actual example hasn't quite elucidated the issue to me.

Can someone explain this in a very basic way and similarly, what would be alternatives to using the Factory Pattern? Perhaps this code that was provided in this exercise oversimplified the issue and this is why I am not clear on what the Factory accomplished. Thank you for some help as some real world color would help greatly. I have read about various design patterns and know what they are but I don't understand the issue well enough having limited real world experience with them

答案1

得分: 2

工厂的基本思想有两个方面:

  1. 对用户(开发者)进行模糊化,隐藏对象的创建方式。
  2. 将所有对象的创建都经过一个统一的起始点。

为什么需要工厂呢?
最简单的答案是,这样你可以控制对象的创建过程。

让我们来看一个现实世界的例子:

你想为你的应用程序编写分析功能。
你愉快地编写了一个实现了你使用的分析库的类。
然后,在你的整个应用程序中编写 AnalyticsEventManager().sendEvent(blabla)
问题是什么?

  1. 总有一天你想添加另一个分析功能或者替换当前的分析功能。
  2. 你如何检查所有需要分析功能的地方是否确实调用了它?

好了,工厂就派上用场了。

与其使用 AnalyticsEventManager().sendEvent(blabla),你可以编写一个拥有 "sendEvent" 方法的接口:

interface AnalyticEventSender {
    void sendEvent(String eventData); 
}

然后你可以创建几个不同类的实例来实现这个分析功能:

class FacebookAnalytic implements AnalyticEventSender {
    @Override
    public void sendEvent(String eventData){
        System.out.println("I am facebook analytics sender:" + eventData);
    }
}

class TestAnalytic implements AnalyticEventSender {
    @Override
    public void sendEvent(String eventData){
        System.out.println("I am test analytics sender:"+eventData);
    }
}

接着你可以创建一个分析工厂:

class AnalyticFactory {
    public static AnalyticEventSender create(){
        if(allowFacebookAnalytic){
            return new FacebookAnalytic();
        }else {
            return new TestAnalytic();
        }
    }
}

这样,你只需根据某个布尔值(更改分析的原因由编写代码的人决定)就能够替换所有分析功能的实例。

现在,不再使用 AnalyticEventManager().sendEvent,而是使用 AnalyticFactory.create().sendEvent(blabla)

所以现在,如果你想检查你的事件是否按照你想要的方式打印出来,只需在工厂中替换返回的实例为 TestAnalytic,然后检查事件是否被打印,而不必经过真正的 Facebook 模块。

这对于许多其他应用程序也是适用的,不仅仅是分析功能。

英文:

The basic idea of a factory is 2 things:

  1. Obfuscate to the user (the developer) how objects are created
  2. Put all object creation through a single place of origin.

Why do you need the factory in the first place?
Well the easiest answer is so that you could control the object creation.

Let's take a real world example:

You want to write an analytics for your app.
You happily write a class that implements some library for analytics that you use.
And go over all of your app and write AnalyticsEventManager().sendEvent(blabla)
What is the problem with this?

  1. There came a day you want to add another analytic or replace the
    current one
  2. How do you check that all the places you need the analytic it is actually invoked?

Well factory to the rescue.

instead of AnalyticsEventManager().sendEvent(blabla)

You write an interface that has a "sendEvent" method

interface AnalyticEventSender {
void sendEvent(String eventData); 
}

Then you have a few instances of different classes that implement this analytic

class FacebookAnalytic implements AnalyticEventSender {
@Override
public void sendEvent(String eventData){
System.out.println("I am facebook analytics sender:" + eventData);
}
}

Then you have

class TestAnalytic implements AnalyticEventSender {
@Override
public void sendEvent(String eventData){
System.out.println("I am test analytics sender:"+eventData);
}
}

Then you have analytic factory

class AnalyticFactory {
public static AnalyticEventSender create(){
if(allowFacebookAnalytic){
return new FacebookAnalytic();
}else {
return new TestAnalytic();
}
}
}

and so just like that you were able to replace ALL the instances of your analytic based on some boolean (the reason for changing the analytic is up to the discretion of the one who wrote the code)

And now instead of doing AnalyticEventManager().sendEvent you would write AnalyticFactory.create().sendEvent(blabla)

So now, If you want to check that your events are actually printed the way you want them to be printed, you just replace the instance that is returned in the factory with the TestAnalytic and check that the events are printed, without actually going through the real facebook module.

This is true for many other applications, not just analytics.

答案2

得分: 1

我建议您阅读《Effective Java》第三版,作者是Joshua Bloch,第一条建议。您可以在Google上查找,但其中一个链接是Effective Java,第三版

英文:

I suggest you read Effective Java, 3rd Edition, by Joshua Bloch, Item 1. You can look it up in Google, but one of the links is Effective Java, 3rd Edition.

huangapple
  • 本文由 发表于 2020年4月8日 17:26:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/61097417.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定