这两种模式的意图和应用有什么区别?

发布于 2024-07-24 22:11:27 字数 1715 浏览 13 评论 0 原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(19

感受沵的脚步 2024-07-31 22:11:27

使用工厂模式,您可以生成特定接口的实现实例(AppleBananaCherry 等)——例如,<代码>IFruit。

使用抽象工厂模式,您可以为任何人提供一种提供自己的工厂的方法。 这允许您的仓库是 IFruitFactoryIJuiceFactory,而不要求您的仓库了解有关水果或果汁的任何信息。

With the Factory pattern, you produce instances of implementations (Apple, Banana, Cherry, etc.) of a particular interface -- say, IFruit.

With the Abstract Factory pattern, you provide a way for anyone to provide their own factory. This allows your warehouse to be either an IFruitFactory or an IJuiceFactory, without requiring your warehouse to know anything about fruits or juices.

乖乖兔^ω^ 2024-07-31 22:11:27

此信息来源取自:http://java.dzone.com /新闻/intro-design-patterns-abstract

抽象工厂与工厂方法

抽象工厂的方法作为工厂方法实现。 抽象工厂模式和工厂方法模式都通过抽象类型和工厂将客户端系统与实际实现类解耦。
工厂方法通过继承创建对象,而抽象工厂通过组合创建对象。

抽象工厂模式由 AbstractFactory、ConcreteFactory、AbstractProduct、ConcreteProduct 和 Client 组成。

如何实现

抽象工厂模式可以使用工厂方法模式、原型模式或单例模式来实现。 ConcreteFactory 对象可以作为 Singleton 实现,因为只需要 ConcreteFactory 对象的一个​​实例。

工厂方法模式是抽象工厂模式的简化版本。 工厂方法模式负责创建属于一个系列的产品,而抽象工厂模式则处理多个系列的产品。

工厂方法使用接口和抽象类将客户端与生成器类和结果产品解耦。 抽象工厂有一个生成器,它是多个工厂方法的容器,以及将客户端与生成器和产品解耦的接口。

何时使用工厂方法模式

当需要将客户端与其使用的特定产品解耦时,请使用工厂方法模式。 使用工厂方法可以减轻客户创建和配置产品实例的责任。

何时使用抽象工厂模式

当客户端必须与产品类解耦时,请使用抽象工厂模式。
对于程序配置和修改特别有用。 抽象工厂模式还可以强制限制哪些类必须与其他类一起使用。 建造新的混凝土工厂可能需要大量工作。

示例:

Abstract Factory 示例 1

此规范用于准备不同类型面食的磁盘
面条机中的抽象工厂是抽象工厂,每个特定的磁盘都是一个工厂。
所有工厂(面条机磁盘)都从抽象工厂继承其属性。
每个单独的磁盘都包含如何制作意大利面的信息,而意大利面制作机则没有。

抽象工厂示例2:

冲压设备对应于抽象工厂,它是一个
用于创建抽象产品对象的操作的接口。
模具对应于混凝土工厂,因为它们制造混凝土产品。
每个零件类别(引擎盖、门等)都对应于抽象产品。
具体部件(即99凯美瑞的驾驶员侧车门)对应于
混凝土产品。

工厂方法示例:

玩具公司对应于创建者,因为它可以使用工厂来创建产品对象。 生产特定类型玩具(马或汽车)的玩具公司的部门对应于 ConcreteCreator。

Source for this information taken from: http://java.dzone.com/news/intro-design-patterns-abstract

Abstract Factory vs. Factory Method

The methods of an Abstract Factory are implemented as Factory Methods. Both the Abstract Factory Pattern and the Factory Method Pattern decouples the client system from the actual implementation classes through the abstract types and factories.
The Factory Method creates objects through inheritance where the Abstract Factory creates objects through composition.

The Abstract Factory Pattern consists of an AbstractFactory, ConcreteFactory, AbstractProduct, ConcreteProduct and Client.

How to implement

The Abstract Factory Pattern can be implemented using the Factory Method Pattern, Prototype Pattern or the Singleton Pattern. The ConcreteFactory object can be implemented as a Singleton as only one instance of the ConcreteFactory object is needed.

Factory Method pattern is a simplified version of Abstract Factory pattern. Factory Method pattern is responsible for creating products that belong to one family, while Abstract Factory pattern deals with multiple families of products.

Factory Method uses interfaces and abstract classes to decouple the client from the generator class and the resulting products. Abstract Factory has a generator that is a container for several factory methods, along with interfaces decoupling the client from the generator and the products.

When to Use the Factory Method Pattern

Use the Factory Method pattern when there is a need to decouple a client from a particular product that it uses. Use the Factory Method to relieve a client of responsibility for creating and configuring instances of a product.

When to Use the Abstract Factory Pattern

Use the Abstract Factory pattern when clients must be decoupled from product classes.
Especially useful for program configuration and modification. The Abstract Factory pattern can also enforce constraints about which classes must be used with others. It may be a lot of work to make new concrete factories.

Examples:

Abstract Factory Example 1

This specification for the disks to prepare different types of pasta
in a pasta maker is the Abstract Factory, and each specific disk is a Factory.
all Factories (pasta maker disks) inherit their properties from the abstract Factory.
Each individual disk contains the information of how to create the pasta, and the pasta maker does not.

Abstract Factory Example 2:

The Stamping Equipment corresponds to the Abstract Factory, as it is an
interface for operations that create abstract product objects.
The dies correspond to the Concrete Factory, as they create a concrete product.
Each part category (Hood, Door, etc.) corresponds to the abstract product.
Specific parts (i.e., driver side door for 99 camry) corresponds to
the concrete products.

Factory Method Example:

The toy company corresponds to the Creator, since it may use the factory to create product objects. The division of the toy company that manufactures a specific type of toy (horse or car) corresponds to the ConcreteCreator.

徒留西风 2024-07-31 22:11:27

工厂模式:
工厂生产 IProduct-implementations

抽象工厂模式:
工厂-工厂生产 IFactories,进而生产 IProducts :)

[根据评论更新]
至少根据维基百科,我之前写的内容是不正确的。 抽象工厂只是一个工厂接口。 有了它,您可以在运行时切换工厂,以允许不同上下文中的不同工厂。 例如,不同操作系统的不同工厂、SQL 提供程序、中间件驱动程序等。

Factory pattern:
The factory produces IProduct-implementations

Abstract Factory Pattern:
A factory-factory produces IFactories, which in turn produces IProducts :)

[Update according to the comments]
What I wrote earlier is not correct according to Wikipedia at least. An abstract factory is simply a factory interface. With it, you can switch your factories at runtime, to allow different factories in different contexts. Examples could be different factories for different OS'es, SQL providers, middleware-drivers etc..

停顿的约定 2024-07-31 22:11:27

抽象工厂模式

  • 提供用于创建的接口
    有亲属关系或受抚养人的家庭
    对象而不指定它们的
    具体类。

  • 抽象工厂模式非常
    类似于工厂方法
    图案。 之间的一处区别是
    二是抽象工厂
    模式,一个类委托
    对象的责任
    通过实例化到另一个对象
    组成而工厂
    方法模式使用继承和
    依赖子类来处理
    所需的对象实例化。

  • 实际上,委托对象
    经常使用工厂方法
    执行实例化!

工厂模式

  • 工厂模式的例子
    创作模式

  • 创造模式抽象了
    对象实例化过程。 他们
    隐藏对象的创建方式和帮助
    使整个系统独立
    它的对象是如何创建的以及
    组成。

  • 类创建模式重点关注
    使用继承来决定
    要实例化的对象
    工厂方法

  • 对象创建模式重点关注
    实例化的委托
    到另一个对象
    抽象工厂

参考:
工厂与抽象工厂

The Abstract Factory Pattern

  • Provide an interface for creating
    families of related or dependent
    objects without specifying their
    concrete classes.

  • The Abstract Factory pattern is very
    similar to the Factory Method
    pattern. One difference between the
    two is that with the Abstract Factory
    pattern, a class delegates the
    responsibility of object
    instantiation to another object via
    composition whereas the Factory
    Method pattern uses inheritance and
    relies on a subclass to handle the
    desired object instantiation.

  • Actually, the delegated object
    frequently uses factory methods to
    perform the instantiation!

Factory pattern

  • Factory patterns are examples of
    creational patterns

  • Creational patterns abstract the
    object instantiation process. They
    hide how objects are created and help
    make the overall system independent
    of how its objects are created and
    composed.

  • Class creational patterns focus on
    the use of inheritance to decide the
    object to be instantiated
    Factory Method

  • Object creational patterns focus on
    the delegation of the instantiation
    to another object
    Abstract Factory

Reference:
Factory vs Abstract Factory

眼眸印温柔 2024-07-31 22:11:27

基本区别:

工厂: 创建对象而不向客户端公开实例化逻辑。

工厂方法:定义一个用于创建对象的接口,但让子类决定实例化哪个类。

抽象工厂:提供用于创建相关对象系列的接口

AbstractFactory模式使用组合来委托对象创建的责任。

工厂方法模式使用继承并为派生类创建对象

示例:StaticFactory

 public class VehicleFactory {

   //Vehicle factory
   public static Vehicle getVehicle(String type){
      if(type == null){
         return null;
      }     
      if(type.equalsIgnoreCase("Car")){
         return new Car();
         
      } else if(type.equalsIgnoreCase("Truck")){
         return new Truck();
         
      } else if(type.equalsIgnoreCase("Bicycle")){
         return new Bicycle();
      }
      
      return null;
   }
}

何时使用:客户端只需要一个类并且不关心它正在得到哪个具体的实现。

工厂方法

何时使用: 客户端不知道在运行时需要创建哪些具体类,而只是想获得一个可以完成这项工作的类。

抽象工厂

何时使用:当您的系统必须在不公开实现细节的情况下创建多个产品系列时。

Basic difference:

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.

Abstract Factory: Provides an interface for creating families of related objects

AbstractFactory pattern uses composition to delegate responsibility of object creation.

Factory method pattern uses inheritance and for derived class to create object

Example: StaticFactory

 public class VehicleFactory {

   //Vehicle factory
   public static Vehicle getVehicle(String type){
      if(type == null){
         return null;
      }     
      if(type.equalsIgnoreCase("Car")){
         return new Car();
         
      } else if(type.equalsIgnoreCase("Truck")){
         return new Truck();
         
      } else if(type.equalsIgnoreCase("Bicycle")){
         return new Bicycle();
      }
      
      return null;
   }
}

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

Factory Method

When to use: 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.

Abstract Factory

When to use: When your system has to create multiple families of products without exposing the implementation details.

一桥轻雨一伞开 2024-07-31 22:11:27

工厂方法:你有一个工厂,它创建从特定基类派生的对象

抽象工厂:你有一个工厂,它创建其他工厂,这些工厂又创建从基类派生的对象。 这样做是因为您通常不仅仅想创建单个对象(与工厂方法一样) - 相反,您想创建相关对象的集合。

Factory method: You have a factory that creates objects that derive from a particular base class

Abstract factory: You have a factory that creates other factories, and these factories in turn create objects derived from base classes. You do this because you often don't just want to create a single object (as with Factory method) - rather, you want to create a collection of related objects.

生寂 2024-07-31 22:11:27

抽象工厂是用于创建相关对象的接口,而工厂方法是一种方法。 抽象工厂是通过工厂方法来实现的。

在此处输入图像描述

Abstract factory is an interface for creating related objects but factory method is a method. Abstract factory is implemented by factory method.

enter image description here

迟到的我 2024-07-31 22:11:27

也许很多人会感到惊讶,但这个问题是不正确的。 如果你在面试中听到这个问题,你需要帮助面试官理解困惑在哪里。

让我们从以下事实开始:不存在仅称为“工厂”的具体模式。 有一种模式称为“抽象工厂”,也有一种模式称为“工厂方法”。

那么,“工厂”是什么意思呢? 以下之一(所有都可以被认为是正确的,具体取决于参考的范围):

  • 有些人将其用作“抽象工厂”。
  • 有些人将其用作“工厂方法”的别名(快捷方式)。
  • 有些人将其用作所有工厂/创建模式的更通用名称。 例如“抽象工厂”和“工厂方法”都是工厂。

而且,不幸的是,许多人使用“工厂”来表示另一种工厂,它创建一个或多个工厂(或其接口)。 根据他们的理论:

Product 实现了 IProduct,它是由 Factory 创建的,
实现 IFactory,它是由 AbstractFactory 创建的。

为了理解这是多么愚蠢,让我们继续我们的方程:

AbstractFactory 实现了 IAbstractFactory,它是由...创建的
抽象抽象工厂???

我希望你明白这一点。 不要感到困惑,也请不要发明一些不存在的东西。

-

PS:产品工厂是 AbstractFactory,抽象工厂工厂也是 AbstractFactory 的另一个例子。

Many people will feel surprised maybe, but this question is incorrect. If you hear this question during an interview, you need to help the interviewer understand where the confusion is.

Let's start from the fact that there is no concrete pattern that is called just "Factory". There is pattern that is called "Abstract Factory", and there is pattern that is called "Factory Method".

So, what does "Factory" mean then? one of the following (all can be considered correct, depending on the scope of the reference):

  • Some people use it as an alias (shortcut) for "Abstract Factory".
  • Some people use it as an alias (shortcut) for "Factory Method".
  • Some people use it as a more general name for all factory/creational patterns. E.g. both "Abstract Factory" and "Factory Method" are Factories.

And, unfortunately, many people use "Factory" to denote another kind of factory, that creates factory or factories (or their interfaces). Based on their theory:

Product implements IProduct, which is created by Factory, which
implements IFactory, which is created by AbstractFactory.

To understand how silly this is, let's continue our equation:

AbstractFactory implements IAbstractFactory, which is created by...
AbstractAbstractFactory???

I hope you see the point. Don't get confused, and please don't invent things that don't exist for reason.

-

P.S.: Factory for Products is AbstractFactory, and Factory for Abstract Factories would be just another example of AbstractFactory as well.

冬天旳寂寞 2024-07-31 22:11:27

抽象工厂的示例/场景

我住在一个雨季下雨、冬天下雪、夏天炎热晴朗的地方。 我需要不同类型的衣服来保护自己免受恶劣天气的影响。 为此,我会去我家附近的商店购买衣服/物品来保护自己。 店主根据环境和我的口袋深度给我合适的物品。 他给我的物品具有相同的质量水平和价格范围。 因为他知道我的标准,所以他很容易做到这一点。 但当街对面的一个有钱人提出同样的要求时,他会得到一件昂贵的品牌商品。 值得注意的一件事是他给我的所有物品在质量、标准和成本方面都是互补的。 可以说他们是相伴而行的。 这位有钱人得到的物品也是如此。

看到上面的场景,我现在体会到店主的办事效率了。 我可以用抽象商店代替这个店主。 我们通过抽象项目获得的项目以及我和作为潜在客户的富人。 我们所需要的只是适合我们需求的产品/项目。

现在,我可以很容易地想到自己正在考虑开设一家为其众多客户提供一系列服务的在线商店。 每个客户都属于三个组之一。 当高级组用户打开该网站时,他会获得出色的用户界面、高度定制的广告窗格、菜单中的更多选项等。这些相同的功能集会呈现给黄金用户,但菜单中的功能较少,广告大多是相关的,以及稍微不那么经济的用户界面。 最后是我的用户类型,“自由组”用户。 我得到了足够的服务,这样我就不会被冒犯。 用户界面是最低限度的,广告太偏离轨道了,我不知道里面有什么,最后菜单只能退出。

如果我有机会建立像这个网站这样的东西,我肯定会考虑抽象工厂模式。

抽象产品:广告窗格、菜单、UI 画家。
抽象工厂:网上商店用户体验
Concreate Factory:高级用户体验、金牌用户体验、一般用户体验。

Example/Scenario for Abstract Factory

I live in a place where it rains in the rainy season, snows in winter and hot and sunny in summers. I need different kind of clothes to protect myself from the elements. To do so I go to the store near my house and ask for clothing/items to protect myself. The store keeper gives me the appropriate item as per the environment and depth of my pocket. The items he gives me are of same level of quality and price range. Since he is aware of my standards its easy for him to do so. But when a rich guy from across the street comes up with the same requirements he gets an expensive, branded item. One noticeable thing is all the items he gives to me complement each other in term quality, standard and cost. One can say they go with each other. Same is the case with the items this rich guy gets.

So by looking at above scenario, I now appreciate the efficiency of the shop keeper. I can replace this shopkeeper with an Abstract Shop. The items we get with abstract items and me and the rich as perspective clients. All we need is the product/item which suits our needs.

Now I can easily see myself considering an online store which provides a set of services to its numerous clients. Each client belongs to one of the three groups. When a premium group user opens up the site he gets great UI, highly customised advertisement pane, more options in the menus etc. These same set of features are presented to gold user but the functionality in the menu is less, advertisements are mostly relevent, and slightly less egronomic UI. Last is my kind of user, a ‘free group’ user. I am just served enough so that I do not get offended. The UI is a bare minimum, advertisements are way off track so much so that I do not know what comes in it, lastly the menu has only log out.

If I get a chance to build something like this website I would definitely consider Abstract Factory Pattern.

Abstract Products : Advertisement Pane, Menu, UI painter.
Abstract Factory : Web Store User Experience
Concreate Factory: Premium User Experience, Gold User Experience, General User Experience.

不美如何 2024-07-31 22:11:27
//Abstract factory - Provides interface to create factory of related products
interface PizzaIngredientsFactory{    
   public Dough createDough(); //Will return you family of Dough
   public Clam createClam();   //Will return you family of Clam
   public Sauce createSauce(); //Will return you family of Sauce
}

class NYPizzaIngredientsFactory implements PizzaIngredientsFactory{

   @Override
   public Dough createDough(){
      //create the concrete dough instance that NY uses
      return doughInstance;
   }

   //override other methods
} 

其他答案已经提供了教科书的定义。 我想我也可以提供一个例子。

因此,这里的 PizzaIngredientsFactory 是一个抽象工厂,因为它提供了创建相关产品系列的方法。

请注意,抽象工厂中的每个方法本身就是一个工厂方法createDough() 本身就是一个工厂方法,其具体实现将由 NYPizzaIngrdientsFactory 等子类提供。 因此,使用这个每个不同的位置都可以创建属于其位置的具体成分的实例。

工厂方法

提供具体实现实例

示例中:
- createDough() - 提供面团的具体实现。 所以这是一个工厂方法

Abstract Factory

提供接口来创建相关对象系列

在示例中:
- PizzaIngredientsFactory 是一个抽象工厂,因为它允许创建一组相关的对象,例如 DoughClamsSauce 。 为了创建每个对象系列,它提供了一个工厂方法。

Head First 设计模式 中的示例

//Abstract factory - Provides interface to create factory of related products
interface PizzaIngredientsFactory{    
   public Dough createDough(); //Will return you family of Dough
   public Clam createClam();   //Will return you family of Clam
   public Sauce createSauce(); //Will return you family of Sauce
}

class NYPizzaIngredientsFactory implements PizzaIngredientsFactory{

   @Override
   public Dough createDough(){
      //create the concrete dough instance that NY uses
      return doughInstance;
   }

   //override other methods
} 

The text book definitions are already provided by other answers. I thought I would provide an example of it too.

So here the PizzaIngredientsFactory is an abstract factory as it provides methods to create family of related products.

Note that each method in the Abstract factory is an Factory method in itself. Like createDough() is in itself a factory method whose concrete implementations will be provided by subclasses like NYPizzaIngredientsFactory. So using this each different location can create instances of concrete ingredients that belong to their location.

Factory Method

Provides instance of concrete implementation

In the example:
- createDough() - provides concrete implementation for dough. So this is a factory method

Abstract Factory

Provides interface to create family of related objects

In the example:
- PizzaIngredientsFactory is an abstract factory as it allows to create a related set of objects like Dough, Clams, Sauce. For creating each family of objects it provides a factory method.

Example from Head First design patterns

满身野味 2024-07-31 22:11:27

通过定义我们可以看出两者的区别:

工厂:接口用于创建对象,但子类决定实例化哪个类。 对象的创建是在需要时完成的。

抽象工厂:抽象工厂模式充当创建其他工厂的超级工厂。 在抽象工厂模式中,接口负责创建一组相关对象或依赖对象,而不指定它们的具体类。

因此,在上面的定义中,我们可以强调一个特定的差异。 即工厂模式负责创建对象,抽象工厂负责创建一组相关的对象; 显然都是通过一个接口。

工厂模式:

public interface IFactory{
  void VehicleType(string n);
 }

 public class Scooter : IFactory{
  public void VehicleType(string n){
   Console.WriteLine("Vehicle type: " + n);
  }
 }

 public class Bike : IFactory{
  public void VehicleType(string n) {
  Console.WriteLine("Vehicle type: " + n);
  }
 }

 public interface IVehicleFactory{
  IFactory GetVehicleType(string Vehicle);
 }

 public class ConcreteVehicleFactory : IVehicleFactory{
 public IFactory GetVehicleType(string Vehicle){
   switch (Vehicle){
    case "Scooter":
     return new Scooter();
    case "Bike":
     return new Bike();
    default:
    return new Scooter();
  }
 }

 class Program{
  static void Main(string[] args){
   IVehicleFactory factory = new ConcreteVehicleFactory();
   IFactory scooter = factory.GetVehicleType("Scooter");
   scooter.VehicleType("Scooter");

   IFactory bike = factory.GetVehicleType("Bike");
   bike.VehicleType("Bike");

   Console.ReadKey();
 }
}

抽象工厂模式:

interface IVehicleFactory{
 IBike GetBike();
 IScooter GetScooter();
}

class HondaFactory : IVehicleFactory{
     public IBike GetBike(){
            return new FZS();
     }
     public IScooter GetScooter(){
            return new FZscooter();
     }
 }
class HeroFactory: IVehicleFactory{
      public IBike GetBike(){
            return new Pulsur();
     }
      public IScooter GetScooter(){
            return new PulsurScooter();
     }
}

interface IBike
    {
        string Name();
    }
interface IScooter
    {
        string Name();
    }

class FZS:IBike{
   public string Name(){
     return "FZS";
   }
}
class Pulsur:IBike{
   public string Name(){
     return "Pulsur";
   }
}

class FZscooter:IScooter {
  public string Name(){
     return "FZscooter";
   }
}

class PulsurScooter:IScooter{
  public string Name(){
     return "PulsurScooter";
   }
}

enum MANUFACTURERS
{
    HONDA,
    HERO
}

class VehicleTypeCheck{
        IBike bike;
        IScooter scooter;
        IVehicleFactory factory;
        MANUFACTURERS manu;

        public VehicleTypeCheck(MANUFACTURERS m){
            manu = m;
        }

        public void CheckProducts()
        {
            switch (manu){
                case MANUFACTURERS.HONDA:
                    factory = new HondaFactory();
                    break;
                case MANUFACTURERS.HERO:
                    factory = new HeroFactory();
                    break;
            }

      Console.WriteLine("Bike: " + factory.GetBike().Name() + "\nScooter: " +      factory.GetScooter().Name());
        }
  }

class Program
    {
        static void Main(string[] args)
        {
            VehicleTypeCheck chk = new VehicleTypeCheck(MANUFACTURERS.HONDA);
            chk.CheckProducts();

            chk= new VehicleTypeCheck(MANUFACTURERS.HERO);
            chk.CheckProducts();

            Console.Read();
        }
    }

By Definition we can drag out the differences of two:

Factory: An interface is used for creating an object, but subclass decides which class to instantiate. The creation of object is done when it is required.

Abstract Factory: Abstract Factory pattern acts as a super-factory which creates other factories. In Abstract Factory pattern an interface is responsible for creating a set of related objects, or dependent objects without specifying their concrete classes.

So, in the definitions above we can emphasize on a particular difference. that is, Factory pattern is responsible for creating objects and Abstract Factory is responsible for creating a set of related objects; obviously both through an interface.

Factory pattern:

public interface IFactory{
  void VehicleType(string n);
 }

 public class Scooter : IFactory{
  public void VehicleType(string n){
   Console.WriteLine("Vehicle type: " + n);
  }
 }

 public class Bike : IFactory{
  public void VehicleType(string n) {
  Console.WriteLine("Vehicle type: " + n);
  }
 }

 public interface IVehicleFactory{
  IFactory GetVehicleType(string Vehicle);
 }

 public class ConcreteVehicleFactory : IVehicleFactory{
 public IFactory GetVehicleType(string Vehicle){
   switch (Vehicle){
    case "Scooter":
     return new Scooter();
    case "Bike":
     return new Bike();
    default:
    return new Scooter();
  }
 }

 class Program{
  static void Main(string[] args){
   IVehicleFactory factory = new ConcreteVehicleFactory();
   IFactory scooter = factory.GetVehicleType("Scooter");
   scooter.VehicleType("Scooter");

   IFactory bike = factory.GetVehicleType("Bike");
   bike.VehicleType("Bike");

   Console.ReadKey();
 }
}

Abstract Factory Pattern:

interface IVehicleFactory{
 IBike GetBike();
 IScooter GetScooter();
}

class HondaFactory : IVehicleFactory{
     public IBike GetBike(){
            return new FZS();
     }
     public IScooter GetScooter(){
            return new FZscooter();
     }
 }
class HeroFactory: IVehicleFactory{
      public IBike GetBike(){
            return new Pulsur();
     }
      public IScooter GetScooter(){
            return new PulsurScooter();
     }
}

interface IBike
    {
        string Name();
    }
interface IScooter
    {
        string Name();
    }

class FZS:IBike{
   public string Name(){
     return "FZS";
   }
}
class Pulsur:IBike{
   public string Name(){
     return "Pulsur";
   }
}

class FZscooter:IScooter {
  public string Name(){
     return "FZscooter";
   }
}

class PulsurScooter:IScooter{
  public string Name(){
     return "PulsurScooter";
   }
}

enum MANUFACTURERS
{
    HONDA,
    HERO
}

class VehicleTypeCheck{
        IBike bike;
        IScooter scooter;
        IVehicleFactory factory;
        MANUFACTURERS manu;

        public VehicleTypeCheck(MANUFACTURERS m){
            manu = m;
        }

        public void CheckProducts()
        {
            switch (manu){
                case MANUFACTURERS.HONDA:
                    factory = new HondaFactory();
                    break;
                case MANUFACTURERS.HERO:
                    factory = new HeroFactory();
                    break;
            }

      Console.WriteLine("Bike: " + factory.GetBike().Name() + "\nScooter: " +      factory.GetScooter().Name());
        }
  }

class Program
    {
        static void Main(string[] args)
        {
            VehicleTypeCheck chk = new VehicleTypeCheck(MANUFACTURERS.HONDA);
            chk.CheckProducts();

            chk= new VehicleTypeCheck(MANUFACTURERS.HERO);
            chk.CheckProducts();

            Console.Read();
        }
    }
眼波传意 2024-07-31 22:11:27

我对约翰的回答有一些看法,如下:

抽象工厂是工厂的工厂!

使用“工厂方法”(因为“工厂”是不明确的),您可以生成特定接口的实现(LemonOrange 等)——例如,<代码>IFruit。 该工厂可以称为CitricFruitFactory

但现在您想要创建 CitricFruitFactory 无法创建的另一种水果。 如果您在其中创建一个 Strawberry ,则 CitricFruitFactory 的代码可能没有意义(草莓不是柠檬酸水果!)。

因此,您可以创建一个名为 RedFruitFactory 的新工厂,用于生产 StrawberryRaspberry 等。

就像 John Feminella 所说:
知道如何创建不同种类的水果。”

“使用抽象工厂模式,您可以生成特定工厂接口的实现 - 例如,IFruitFactory。其中每一个都 IFruitFactoryCitricFruitFactoryRedFruitFactory

I have some points to contribute with John's answer as follows:

Abstract factory is a factory of factories!

With the "Factory Method" (because just "Factory" is ambiguous), you produce implementations (Lemon, Orange, etc.) of a particular interface -- say, IFruit. This Factory could be called CitricFruitFactory.

But now you want to create another kinds of fruit that the CitricFruitFactory is not able to create. Maybe the code of CitricFruitFactory wouldn't make sense if you create an Strawberry in it (strawberry is not a citric fruit!).

So you could create a new Factory called RedFruitFactory that produces Strawberry, Raspberry, etc.

Like John Feminella said:
"With the Abstract Factory pattern, you produce implementations of a particular Factory interface -- e.g., IFruitFactory. Each of those knows how to create different kinds of fruit."

That implementatios of IFruitFactory are CitricFruitFactory and RedFruitFactory!

苦妄 2024-07-31 22:11:27

我的来源是:StackOverflowtutorialspoint.comprogrammers.stackexchange.comCodeProject.com


Factory Method(也称为Factory)用于解耦Interface实现的客户端。 例如,我们有一个 Shape 接口,其中有两个 CircleSquare 实现。 我们定义了一个带有工厂方法的工厂类,该方法带有确定参数(例如 Type)以及 Shape 接口的新相关实现。


Abstract Factory 包含多个工厂方法或由多个工厂实现组成的工厂接口。
对于上面的下一个示例,我们有一个 Color 接口,其中包含两个 RedYellow 实现。
我们定义了一个 ShapeColorFactory 接口,其中包含两个 RedCircleFactoryYellowSquareFactory。 下面的代码解释了这个概念:

interface ShapeColorFactory
{
    public Shape getShape();
    public Color getColor();
}

class RedCircleFactory implements ShapeColorFactory
{
    @Override
    public Shape getShape() {
        return new Circle();
    }

    @Override
    public Color getColor() {
        return new Red();
    }
}
class YellowSquareFactory implements ShapeColorFactory
{
    @Override
    public Shape getShape() {
        return new Square();
    }

    @Override
    public Color getColor() {
        return new Yellow();
    }
} 

这是FactoryMethodAbstractFactory之间的区别。 工厂方法简单地返回接口的具体类,但抽象工厂返回工厂的工厂。 换句话说,抽象工厂返回一系列接口的不同组合。


我希望我的解释有用。

My sources are : StackOverflow, tutorialspoint.com, programmers.stackexchange.com and CodeProject.com.


Factory Method (also called Factory) is for decouple client of a Interface implementation. For sample we have a Shape interface with two Circle and Square implementations. We have define a factory class with a factory method with a determiner parameter such as Type and new related implementation of Shape interface.


Abstract Factory contains several factory method or a factory interface by several factory implementations.
For next above sample we have a Color interface with two Red and Yellow implementations.
We have define a ShapeColorFactory interface with two RedCircleFactory and YellowSquareFactory. Following code for explain this concept:

interface ShapeColorFactory
{
    public Shape getShape();
    public Color getColor();
}

class RedCircleFactory implements ShapeColorFactory
{
    @Override
    public Shape getShape() {
        return new Circle();
    }

    @Override
    public Color getColor() {
        return new Red();
    }
}
class YellowSquareFactory implements ShapeColorFactory
{
    @Override
    public Shape getShape() {
        return new Square();
    }

    @Override
    public Color getColor() {
        return new Yellow();
    }
} 

Here difference between FactoryMethod and AbstractFactory. Factory Method as simply return a concrete class of a interface but Abstract Factory return factory of factory. In other words Abstract Factory return different combine of a series of interface.


I hope my explanation useful.

享受孤独 2024-07-31 22:11:27

这些工厂的主要区别在于您何时想要对工厂做什么以及何时想要使用它。

有时,当您进行 IOC(控制反转,例如构造函数注入)时,您知道可以创建实体对象。 正如上面的水果示例中提到的,如果您准备创建水果对象,则可以使用简单的工厂模式

但很多时候,您不想创建实体对象,它们稍后会出现在程序流程中。 但是配置会告诉您要在开始时使用哪种工厂,您可以将从公共工厂类派生的工厂传递给 IOC 中的构造函数,而不是创建对象。

所以,我认为这也与对象的生命周期和创建有关。

The major difference in those factories is when what you want to do with the factories and when you want to use it.

Sometimes, when you are doing IOC (inversion of control e.g. constructor injection), you know that you can create solid objects. As mentioned in the example above of fruits, if you are ready to create objects of fruits, you can use simple factory pattern.

But many times, you do not want to create solid objects, they will come later in the program flow. But the configuration tells you the what kind of factory you want to use at start, instead of creating objects, you can pass on factories which are derived from a common factory class to the constructor in IOC.

So, I think its also about the object lifetime and creation.

北笙凉宸 2024-07-31 22:11:27

扩展 John Feminella 的答案:

AppleBananaCherry 实现了 FruitFactory 并且具有一个名为 Create 的方法,它单独负责创建 Apple、Banana 或 Cherry。 您的 Factory 方法就完成了。

现在,您想用水果创建一种特殊的沙拉,您的抽象工厂就出现了。 Abstract Factory 知道如何用苹果、香蕉和樱桃制作您的特色沙拉。

public class Apple implements Fruit, FruitFactory {
    public Fruit Create() {
        // Apple creation logic goes here
    }
}

public class Banana implements Fruit, FruitFactory {
    public Fruit Create() {
        // Banana creation logic goes here
    }
}

public class Cherry implements Fruit, FruitFactory {
    public Fruit Create() {
        // Cherry creation logic goes here
    }
}

public class SpecialSalad implements Salad, SaladFactory {
    public static Salad Create(FruitFactory[] fruits) {
        // loop through the factory and create the fruits.
        // then you're ready to cut and slice your fruits 
        // to create your special salad.
    }
}

Extending John Feminella answer:

Apple, Banana, Cherry implements FruitFactory and that has a method called Create which is solely responsible of creating Apple or Banana or Cherry. You're done, with your Factory method.

Now, you want to Create a special salad out of your fruits and there comes your Abstract Factory. Abstract Factory knows how to create your special Salad out of the Apple, Banana and Cherry.

public class Apple implements Fruit, FruitFactory {
    public Fruit Create() {
        // Apple creation logic goes here
    }
}

public class Banana implements Fruit, FruitFactory {
    public Fruit Create() {
        // Banana creation logic goes here
    }
}

public class Cherry implements Fruit, FruitFactory {
    public Fruit Create() {
        // Cherry creation logic goes here
    }
}

public class SpecialSalad implements Salad, SaladFactory {
    public static Salad Create(FruitFactory[] fruits) {
        // loop through the factory and create the fruits.
        // then you're ready to cut and slice your fruits 
        // to create your special salad.
    }
}
心凉 2024-07-31 22:11:27

工厂方法和抽象工厂都使客户端与具体类型解耦。 两者都创建对象,但 Factory 方法使用继承,而 Abstract Factory 使用组合。

工厂方法在子类中继承以创建具体对象(产品),而抽象工厂提供用于创建相关产品系列的接口,这些接口的子类定义如何创建相关产品。

然后,这些子类在实例化时被传递到产品类中,并在其中用作抽象类型。 抽象工厂中的相关产品通常使用工厂方法来实现。

Both Factory Method and Abstract Factory keep the clients decoupled from the concrete types. Both create objects, but Factory method uses inheritance whereas Abstract Factory use composition.

The Factory Method is inherited in subclasses to create the concrete objects(products) whereas Abstract Factory provide interface for creating the family of related products and subclass of these interface define how to create related products.

Then these subclasses when instantiated is passed into product classes where it is used as abstract type. The related products in an Abstract Factory are often implemented using Factory Method.

还不是爱你 2024-07-31 22:11:27

检查此处:http://www.allapplabs.com/java_design_patterns/abstract_factory_pattern.htm
工厂方法似乎使用特定的类(非抽象)作为基类,而抽象工厂为此使用抽象类。 此外,如果使用接口而不是抽象类,结果将是抽象工厂模式的不同实现。

:D

Check here: http://www.allapplabs.com/java_design_patterns/abstract_factory_pattern.htm
it seems that Factory method uses a particular class(not abstract) as a base class while Abstract factory uses an abstract class for this. Also if using an interface instead of abstract class the result will be a different implementation of Abstract Factory pattern.

:D

洒一地阳光 2024-07-31 22:11:27

抽象工厂是用于创建不同类型接口的模板。
假设您的项目要求您解析不同类型的 csv 文件,其中包含数量、价格和项目特定信息,例如某些包含有关水果的数据,其他有关巧克力的数据,然后在解析后,您需要在相应的数据库中更新此信息,这样现在您就可以拥有一个抽象工厂返回解析器和修饰符工厂,然后这个解析器工厂可以返回巧克力解析器对象、水果解析器对象等,类似地修改器工厂可以返回巧克力修饰符对象、水果修饰符对象等。

Abstract Factory is template for creating different type of interfaces.
Suppose you have project that requires you to parse different types of csv files containing quantity, price and item specific information like some contain data about fruits other about chocolates and then after parsing you need to update this information in their corresponding database so now you can have one abstract factory returning you parser and modifier factory and then this parser factory can return you Chocolate parser object,Fruit Parser Object etc. and similarly Modifier Factory can return Chocolate modifier object , Fruit Modifier object etc.

寄风 2024-07-31 22:11:27

我认为我们可以通过查看 Java8 示例代码来理解这两者之间的区别:

  interface Something{}

  interface OneWhoCanProvideSomething {
     Something getSomething();
  }

  interface OneWhoCanProvideCreatorsOfSomething{
     OneWhoCanProvideSomething getCreator();
  }


public class AbstractFactoryExample {

    public static void main(String[] args) {
        //I need something
        //Let's create one
        Something something = new Something() {};

        //Or ask someone (FACTORY pattern)
        OneWhoCanProvideSomething oneWhoCanProvideSomethingOfTypeA = () -> null;
        OneWhoCanProvideSomething oneWhoCanProvideSomethingOfTypeB = () -> null;

        //Or ask someone who knows soemone who can create something (ABSTRACT FACTORY pattern)
        OneWhoCanProvideCreatorsOfSomething oneWhoCanProvideCreatorsOfSomething = () -> null;

        //Same thing, but you don't need to write you own interfaces
        Supplier<Something> supplierOfSomething = () -> null;
        Supplier<Supplier<Something>> supplierOfSupplier = () -> null;
    }

}

现在的问题是您应该使用哪种创建方式以及为什么:
第一种方法(没有模式,只是简单的构造函数):自己创建不是一个好主意,您必须完成所有工作,并且您的客户端代码与特定实现相关联。

第二种方式(使用工厂模式):为您提供可以传递任何类型的实现的好处,它可以根据某些条件(可能是传递给创建方法的参数)提供不同类型的东西。

第三种方式(使用抽象工厂模式):这为您提供了更大的灵活性。 您可以根据某些条件(可能是传递的参数)找到某物的不同类型的创建者。

请注意,您总是可以通过将两个条件组合在一起来摆脱工厂模式(这会稍微增加代码复杂性和耦合性),我想这就是为什么我们很少看到抽象工厂模式的现实用例。

I think we can understand the difference between these two by seeing a Java8 example code:

  interface Something{}

  interface OneWhoCanProvideSomething {
     Something getSomething();
  }

  interface OneWhoCanProvideCreatorsOfSomething{
     OneWhoCanProvideSomething getCreator();
  }


public class AbstractFactoryExample {

    public static void main(String[] args) {
        //I need something
        //Let's create one
        Something something = new Something() {};

        //Or ask someone (FACTORY pattern)
        OneWhoCanProvideSomething oneWhoCanProvideSomethingOfTypeA = () -> null;
        OneWhoCanProvideSomething oneWhoCanProvideSomethingOfTypeB = () -> null;

        //Or ask someone who knows soemone who can create something (ABSTRACT FACTORY pattern)
        OneWhoCanProvideCreatorsOfSomething oneWhoCanProvideCreatorsOfSomething = () -> null;

        //Same thing, but you don't need to write you own interfaces
        Supplier<Something> supplierOfSomething = () -> null;
        Supplier<Supplier<Something>> supplierOfSupplier = () -> null;
    }

}

Now the question is which way of creation should you use and why:
The first way (no pattern, just plain constructor): creating by yourself is not a good idea, you have to do all the work, and your client code is tied to the particular implementation.

The second way (using Factory pattern): provides you the benefit that you can pass any type of implementation, which can provide different type of something based on some condition (maybe a parameter passed to creational method).

The third way (using Abstract Factory pattern): This gives you more flexibility. You can find different types of creators of something based on some condition (maybe a parameter passed).

Note that you can always get away with Factory pattern by combining two conditions together (which slightly increases code complexity, and coupling), I guess that's why we rarely see real life use cases of Abstract Factory pattern.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文