工厂设计模式的简洁描述

发布于 2024-09-29 01:38:51 字数 584 浏览 4 评论 0原文

我很难理解工厂设计模式的概念。据我了解,它允许调用代码不必担心单个对象是如何实例化的,只需知道它将实现特定的接口即可。

但我看不出这如何保存任何代码。

例如,如果我有 3 种类型的车辆

lorry, car, van

并且我为每种车辆创建了一个类,我可以只使用 switch 语句。鉴于到目前为止我看到的工厂类的示例,我可以有一个接口:

Interface vehicle {
    method drive();
}

然后是一个类:

Class vehiclefac implements vehicle {
    method createvehicle(type) {
     // choose car type and return
}    
}

我仍然需要使用 switch 语句来选择我的车辆类型,更进一步,如果我想添加新车,我仍然需要将它们添加到 switch 语句的末尾,并创建一个适当的子类来实现它们。

如果有人能澄清我没有得到的信息,我将非常感激,特别感谢 python 中的示例。

Im having trouble getting my head around the concept of the factory design pattern. As far as i understand its to allow calling code not to have to worry about how an individual object is instantiated, simply to know that it will implement a particular interface.

I cant see how this saves any code though.

for instance, if i had 3 types of vehicle

lorry, car, van

and i created a class for each of them, i could just use a switch statement. Whereas with the examples of factory classes ive seen so far, i could have an interface:

Interface vehicle {
    method drive();
}

and then a class:

Class vehiclefac implements vehicle {
    method createvehicle(type) {
     // choose car type and return
}    
}

i still need to use a switch statement to pick my type of vehicle, further to this, if i want to add new cars, i still have to add them to the end of the switch statement and create an appropriate sub class to implement them.

If someone can clear up what im not getting id be very grateful, examples in python especially appreciated.

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

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

发布评论

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

评论(6

以为你会在 2024-10-06 01:38:51

这不是关于减少代码,更多的是关于依赖解耦。如果您对接口进行编码,并使用工厂来检索实例,则不需要知道您正在使用哪个具体类。如果项目稍后有人编写替代实现,则可以将工厂配置为使用新类,而无需修改工厂的客户端。

例如,想象一个为数据序列化创建流对象的工厂。实例可以请求流接口将其自身序列化。根据配置或状态,工厂可以配置为提供写入文件系统的实例。在不同的状态/配置下,它可以给出网络流实现。选择正确实现的工厂逻辑可以根据需求的需要而简单或复杂,但客户端代码不需要了解有关各种实现的任何信息。

项目中不一定需要更少的代码来实现这一点,但代码是松散耦合的并且更容易维护。

It's not about reduction of code, it's more about dependency decoupling. If you code to an interface, and use a factory to retrieve your instances, you don't need to know what concrete class you're using. If later in the project someone writes an alternate implementation, the factory can be configured to use the new class without modifying the factory's clients.

For instance, imagine a factory that created stream objects for data serialization. An instance could request a stream interface to serialize itself to. Depending on configuration or state, the factory could be configured to give instances which write to the filesystem. In a different state/configuration, it could give out network stream implementations. The factory logic which selects the right implementation can be as simple or complex as the requirements need, but the client code doesn't need to know anything about the various implementations.

There isn't necessarily less code in the project to allow this, but the code is loosely coupled and much more easily maintained.

梦里兽 2024-10-06 01:38:51

工厂方法模式是一个创作模式。它可用于构建特定基本类型的对象,而无需指定确切的具体类型,这是由任何输入和工厂内的创建逻辑决定的。

public class VehicleFactory
{
     public IVehicle Create(int noOfWheels)
     {
        if (noOfWheels == 1)
            return new UniCycle();
        if (noOfWheels == 2)
            return new MotorCycle();
        if (noOfWheels == 3)
            return new Trike();
        if (noOfWheels == 4)
            return new Car();

        throw new NotImplementedException();
    }
}

public class UniCycle : IVehcicle { ... }
public class MotorCycle: IVehcicle { ... }
public class Trike: IVehcicle { ... }
public class Car: IVehcicle { ... }

以下是一个简单的 C# 示例,以您的车辆想法为基础。有用之处在于,任何使用代码并不关心具体类是什么,只是它返回一个 IVehicle。它也不必使用接口来完成,尽管我更喜欢它们,但也可以根据情况使用抽象基类来完成。

当我使用工厂模式时,我通常让工厂实现一个接口,这称为抽象工厂模式。对于这个例子,它会是这样的:

public interface IVehicleFactory
{
    IVehicle Create(int noOfWheels);
}

然后可以将工厂注入到类中(参见IoC) 。总而言之,它为您提供:

  • 解耦您的代码。
  • 允许工厂的不同实现。
  • 使用更干净的代码,没有对象实例化。
  • 单元测试更容易,需要担心的复杂具体类也更少。

我为抽象工厂模式提供的 wiki 链接有一些 Python 示例。

The factory method pattern is a Creational pattern. It can be used to build objects of a particular base type with out specifying the exact concrete type, this is determined by any input and the create logic inside the factory.

public class VehicleFactory
{
     public IVehicle Create(int noOfWheels)
     {
        if (noOfWheels == 1)
            return new UniCycle();
        if (noOfWheels == 2)
            return new MotorCycle();
        if (noOfWheels == 3)
            return new Trike();
        if (noOfWheels == 4)
            return new Car();

        throw new NotImplementedException();
    }
}

public class UniCycle : IVehcicle { ... }
public class MotorCycle: IVehcicle { ... }
public class Trike: IVehcicle { ... }
public class Car: IVehcicle { ... }

The following is a simple C# example using your vehicle idea as the basis. The usefulness is that any consuming code doesn't care what the concrete class is just that it gets back an IVehicle. It doesn't have to be done with interfaces either, all though I prefer them, it could also be done with an abstract base class depending on the situation.

When I use the factory pattern I normally have the factory implement an interface, this is called the Abstract Factory Pattern. For this example it would be something like:

public interface IVehicleFactory
{
    IVehicle Create(int noOfWheels);
}

The factory can then be injected into classes (see IoC). All together it gives you:

  • Decouple your code.
  • Allows for different implementations of a factory.
  • Consuming code cleaner, no object instantiation.
  • Unit testing is easier, fewer complex concrete classes to worry about.

The wiki link I have provided for the Abstract Factory Pattern has some examples in Python.

陪你搞怪i 2024-10-06 01:38:51

工厂旨在封装开关逻辑。这意味着您无需担心在需要车辆的任何地方如何创建车辆,并且在添加新类型的车辆时无需在工厂以外的任何地方更改代码。

The factory is meant to encapsulate the switch logic. This means that you don't need to worry about how the vehicle is created everywhere you need a vehicle and you don't need to change code anywhere other than the factory when you add a new type of vehicle.

白色秋天 2024-10-06 01:38:51

将工厂视为“虚拟构造函数”。是的,您必须有一个公共接口,即返回对象的静态类型,但您可以创建任何类型,只要它们实现该公共接口即可。

至于添加新的子类型,您可以通过允许它的语言进行反射来完成。我(还不知道)Python 是否是其中之一。

Think of a factory as a "virtual constructor". Yes, you have to have a common interface, and that is the static type of the object returned, but you can create any type as long as they implement that common interface.

As for adding new subtypes, you can do it with reflection in languages that allow it. I don't know (yet) if Python is one of them.

雪若未夕 2024-10-06 01:38:51

看看这里:
这是工厂方法创建模式吗?
他们对你的问题有争议。

Have a look here:
Is this Factory Method creation pattern?
They dispute on your problem.

魔法唧唧 2024-10-06 01:38:51

工厂方法模式是一种创建模式。它封装了针对特定情况应创建相同对象层次结构的专门化的逻辑。

The factory method pattern is a Creational pattern. It encapsulate the logic on what specialization of the same object hierarchy should be created for a particular case.

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