设计模式。工厂VS工厂方法VS抽象工厂[英] Design Patterns: Factory vs Factory method vs Abstract Factory

本文是小编为大家收集整理的关于设计模式。工厂VS工厂方法VS抽象工厂的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我正在阅读网站的设计模式

我在那里阅读了有关工厂,工厂方法和抽象工厂的信息,但它们是如此令人困惑,在定义上尚不清楚.根据定义

工厂 - 创建对象而无需将实例化逻辑公开给客户端,并通过公共接口引用新创建的对象. 是工厂方法的简化版本

出厂方法 - 定义用于创建对象的接口,但让子类决定要实例化的类并通过公共接口引用新创建的对象.

抽象工厂 - 提供用于创建相关对象家族的接口,而无需明确指定其类.

我还查看了有关抽象工厂与工厂方法的其他stackoverflow线程,但是在那里绘制的UML图使我的理解变得更糟.

任何人都可以告诉我

  1. 这三种模式彼此之间有何不同?
  2. 什么时候使用?
  3. 以及如果可能的话,任何与这些模式有关的Java示例?

推荐答案

所有三种工厂类型都做同样的事情:它们是"智能构造函数".

假设您希望能够创建两种水果:苹果和橙色.

工厂

工厂是"固定的",因为您只有一个没有子类的实现.在这种情况下,您将有这样的课程:
class FruitFactory {

  public Apple makeApple() {
    // Code for creating an Apple here.
  }

  public Orange makeOrange() {
    // Code for creating an orange here.
  }

}

用例:构建苹果或橙色有点复杂,无法在构造函数中处理.

工厂方法

当您在课堂中进行一些通用处理时,通常使用工厂方法,但想改变您实际使用的水果.所以:
abstract class FruitPicker {

  protected abstract Fruit makeFruit();

  public void pickFruit() {
    private final Fruit f = makeFruit(); // The fruit we will work on..
    <bla bla bla>
  }
}

...然后,您可以通过在子类中实现工厂方法来重复使用FruitPicker.pickFruit()中的共同功能:

class OrangePicker extends FruitPicker {

  @Override
  protected Fruit makeFruit() {
    return new Orange();
  }
}

抽象工厂

抽象工厂通常用于依赖注入/策略之类的事物,当您想创建一个需要"同类"并具有一些共同基础类的对象时.这是一个模糊的水果相关的例子.这里的用例是,我们要确保不要在苹果上意外使用橙皮.只要我们从同一工厂获得水果和采摘者,它们就会匹配.
interface PlantFactory {
  
  Plant makePlant();

  Picker makePicker(); 

}

public class AppleFactory implements PlantFactory {
  Plant makePlant() {
    return new Apple();
  }

  Picker makePicker() {
    return new ApplePicker();
  }
}

public class OrangeFactory implements PlantFactory {
  Plant makePlant() {
    return new Orange();
  }

  Picker makePicker() {
    return new OrangePicker();
  }
}

其他推荐答案

  1. 这三种模式彼此之间有何不同?

工厂:创建对象而不将实例化逻辑公开给客户端.

出厂方法:定义用于创建对象的接口,但让子类决定要实例化哪个类.工厂方法使课堂递延实例化为子类

摘要工厂:提供了一个界面,用于创建相关对象的家庭,而无需指定其具体类.

AbstractFactory 模式使用构图来委派将对象创建为另一类的责任,而 factory方法设计模式设计模式使用继承,并依靠派生的类或子类来创建对象

  1. 什么时候使用?

工厂:客户只需要一堂课,并且不在乎它正在获得的具体实现.

出厂方法:客户不知道在运行时创建需要什么具体类,而只是想获得可以完成工作的课程.

abstactfactory:当您的系统必须创建多个产品家族或您要提供产品库而不揭示实施细节时.

抽象工厂类通常用工厂方法实现.工厂方法通常在模板方法中调用.

  1. 以及如果可能的话,任何与这些模式有关的Java示例?

工厂和工厂

意图:

定义用于创建对象的接口,但让子类决定要实例化的类.工厂方法让课堂延期启动为子类.

uml图:

在此处输入图像说明

产品:它定义了出厂方法创建的对象的接口.

concreteproduct:实现产品接口

创建者:声明工厂方法

ConcreateCreator:实现了返回Concreteproduct实例的工厂方法

问题语句:使用工厂方法来创建游戏工厂,该方法定义了游戏接口.

代码段:

工厂模式.什么时候使用工厂方法?

与其他创建模式进行比较:

  1. 设计首先使用工厂方法(较少复杂,更可定制,子类增殖),然后朝着抽象工厂,原型或构建器发展发展,更复杂的),因为设计师发现需要更多灵活性

  2. Abstract Factory classes are often implemented with Factory Methods, but they can also be implemented using Prototype

参考文献: sourcemaking design-patterns

其他推荐答案

基于此图像,来自 c#中的设计模式,第二版,vaskaran sarcar 书:

1.简单的工厂模式

创建对象而不将实例化逻辑公开给客户端.

SimpleFactory simpleFactory = new SimpleFactory();
IAnimal dog = simpleFactory.CreateDog(); // Create dog
IAnimal tiger = simpleFactory.CreateTiger(); // Create tiger

在此处输入图像说明

2.工厂方法模式

定义用于创建对象的接口,但让子类决定要实例化的类.

AnimalFactory dogFactory = new DogFactory(); 
IAnimal dog = dogFactory.CreateAnimal(); // Create dog

AnimalFactory tigerFactory = new TigerFactory();
IAnimal tiger = tigerFactory.CreateAnimal(); // Create tiger

在此处输入图像说明

3.抽象工厂模式(工厂工厂)

摘要工厂提供了用于创建相关对象家族的接口,而无需明确指定其类

IAnimalFactory petAnimalFactory = FactoryProvider.GetAnimalFactory("pet");
IDog dog = petAnimalFactory.GetDog(); // Create pet dog
ITiger tiger = petAnimalFactory.GetTiger();  // Create pet tiger

IAnimalFactory wildAnimalFactory = FactoryProvider.GetAnimalFactory("wild");
IDog dog = wildAnimalFactory .GetDog(); // Create wild dog
ITiger tiger = wildAnimalFactory .GetTiger();  // Create wild tiger

在此处输入图像说明

本文地址:https://www.itbaoku.cn/post/627528.html

问题描述

I was reading design patterns from a website

There I read about Factory, Factory method and Abstract factory but they are so confusing, am not clear on the definition. According to definitions

Factory - Creates objects without exposing the instantiation logic to the client and Refers to the newly created object through a common interface. Is a simplified version of Factory Method

Factory Method - Defines an interface for creating objects, but let subclasses to decide which class to instantiate and Refers to the newly created object through a common interface.

Abstract Factory - Offers the interface for creating a family of related objects, without explicitly specifying their classes.

I also looked the other stackoverflow threads regarding Abstract Factory vs Factory Method but the UML diagrams drawn there make my understanding even worse.

Can anyone please tell me

  1. How are these three patterns different from each other?
  2. When to use which?
  3. And also if possible, any java examples related to these patterns?

推荐答案

All three Factory types do the same thing: They are a "smart constructor".

Let's say you want to be able to create two kinds of Fruit: Apple and Orange.

Factory

Factory is "fixed", in that you have just one implementation with no subclassing. In this case, you will have a class like this:
class FruitFactory {

  public Apple makeApple() {
    // Code for creating an Apple here.
  }

  public Orange makeOrange() {
    // Code for creating an orange here.
  }

}

Use case: Constructing an Apple or an Orange is a bit too complex to handle in the constructor for either.

Factory Method

Factory method is generally used when you have some generic processing in a class, but want to vary which kind of fruit you actually use. So:
abstract class FruitPicker {

  protected abstract Fruit makeFruit();

  public void pickFruit() {
    private final Fruit f = makeFruit(); // The fruit we will work on..
    <bla bla bla>
  }
}

...then you can reuse the common functionality in FruitPicker.pickFruit() by implementing a factory method in subclasses:

class OrangePicker extends FruitPicker {

  @Override
  protected Fruit makeFruit() {
    return new Orange();
  }
}

Abstract Factory

Abstract factory is normally used for things like dependency injection/strategy, when you want to be able to create a whole family of objects that need to be of "the same kind", and have some common base classes. Here's a vaguely fruit-related example. The use case here is that we want to make sure that we don't accidentally use an OrangePicker on an Apple. As long as we get our Fruit and Picker from the same factory, they will match.
interface PlantFactory {
  
  Plant makePlant();

  Picker makePicker(); 

}

public class AppleFactory implements PlantFactory {
  Plant makePlant() {
    return new Apple();
  }

  Picker makePicker() {
    return new ApplePicker();
  }
}

public class OrangeFactory implements PlantFactory {
  Plant makePlant() {
    return new Orange();
  }

  Picker makePicker() {
    return new OrangePicker();
  }
}

其他推荐答案

  1. How are these three patterns different from each other?

Factory: Creates objects without exposing the instantiation logic to the client.

Factory Method: Define an interface for creating an object, but let the subclasses decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses

Abstract Factory: Provides an interface for creating families of related or dependent objects without specifying their concrete classes.

AbstractFactory pattern uses composition to delegate responsibility of creating object to another class while Factory method design pattern uses inheritance and relies on derived class or sub class to create object

  1. When to use which?

Factory: Client just need a class and does not care about which concrete implementation it is getting.

Factory Method: Client doesn't know what concrete classes it will be required to create at runtime, but just wants to get a class that will do the job.

AbstactFactory: When your system has to create multiple families of products or you want to provide a library of products without exposing the implementation details.

Abstract Factory classes are often implemented with Factory Method. Factory Methods are usually called within Template Methods.

  1. And also if possible, any java examples related to these patterns?

Factory and FactoryMethod

Intent:

Define an interface for creating an object, but let sub classes decide which class to instantiate. Factory Method lets a class defer instantiation to sub classes.

UML diagram:

enter image description here

Product: It defines an interface of the objects the Factory method creates.

ConcreteProduct: Implements Product interface

Creator: Declares the Factory method

ConcreateCreator: Implements the Factory method to return an instance of a ConcreteProduct

Problem statement: Create a Factory of Games by using Factory Methods, which defines the game interface.

Code snippet:

Factory Pattern. When to use factory methods?

Comparison with other creational patterns:

  1. Design start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward Abstract Factory, Prototype, or Builder (more flexible, more complex) as the designer discovers where more flexibility is needed

  2. Abstract Factory classes are often implemented with Factory Methods, but they can also be implemented using Prototype

References for further reading: Sourcemaking design-patterns

其他推荐答案

Based this images from Design Patterns in C#, 2nd Edition by Vaskaran Sarcar book:

1. Simple Factory Pattern

Creates objects without exposing the instantiation logic to the client.

SimpleFactory simpleFactory = new SimpleFactory();
IAnimal dog = simpleFactory.CreateDog(); // Create dog
IAnimal tiger = simpleFactory.CreateTiger(); // Create tiger

enter image description here

2. Factory Method Pattern

Defines an interface for creating objects, but let subclasses to decide which class to instantiate.

AnimalFactory dogFactory = new DogFactory(); 
IAnimal dog = dogFactory.CreateAnimal(); // Create dog

AnimalFactory tigerFactory = new TigerFactory();
IAnimal tiger = tigerFactory.CreateAnimal(); // Create tiger

enter image description here

3. Abstract Factory pattern (factory of factories)

Abstract Factory offers the interface for creating a family of related objects, without explicitly specifying their classes

IAnimalFactory petAnimalFactory = FactoryProvider.GetAnimalFactory("pet");
IDog dog = petAnimalFactory.GetDog(); // Create pet dog
ITiger tiger = petAnimalFactory.GetTiger();  // Create pet tiger

IAnimalFactory wildAnimalFactory = FactoryProvider.GetAnimalFactory("wild");
IDog dog = wildAnimalFactory .GetDog(); // Create wild dog
ITiger tiger = wildAnimalFactory .GetTiger();  // Create wild tiger

enter image description here