gpt4 book ai didi

java - 如果我在实现工厂模式时使用抽象类而不是接口(interface)。还会是工厂模式吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:50:01 25 4
gpt4 key购买 nike

例如:http://www.tutorialspoint.com/design_pattern/factory_pattern.htm

如果我更改抽象类 Shape 的接口(interface)形状,创建具体类来扩展 Shape 并使 Shape 工厂返回 Shape 抽象类类型化对象。它仍然是工厂模式吗?

最佳答案

我会同意。

让我们看一下工厂方法模式的定义:

the factory method pattern is a creational pattern which uses factory methods to deal with the problem of creating objects without specifying the exact class of object that will be created

此模式背后的动机是将对象创建与使用该对象的客户端分开。客户应向工厂提供规范,但详细说明如何构建对象被工厂抽象掉。

如果这是一个接口(interface)或抽象类是特定于情况的实现细节,只要您的工厂实现能让您实现模式背后的动机。

如果以下任何陈述适用于您的情况,请考虑使用抽象类:

  • You want to share code among several closely related classes.

  • You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).

  • You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.

如果以下任何陈述适用于您的情况,请考虑使用接口(interface):

  • You expect that unrelated classes would implement your interface. For example, the interfaces Comparable and Cloneable are implemented by many unrelated classes.

  • You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.

  • You want to take advantage of multiple inheritance of type.

在某些实现中,为工厂创建的产品使用抽象类而不是接口(interface)甚至可能更有意义。如果所有产品之间有一组共享的特性/行为,那么将它们放入基本抽象类中确实有意义。即使产品来自不同的工厂,这也适用。

归结为:你想引入耦合吗?引入耦合是否有意义?产品与否?最终,客户将获得相同的结果 - 产品基于规范构建,构建细节被抽象化。

关于java - 如果我在实现工厂模式时使用抽象类而不是接口(interface)。还会是工厂模式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31477625/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com