Как упаковать Фабрики в Java

Я задавался вопросом, как упаковать фабрики, которые я имею в своем приложении. Фабрика должна быть в том же пакете как классы, которые используют его в том же пакете как объекты, которые это создает или в его собственном пакете?

Спасибо за внимание и обратная связь

14
задан Tanmay Patil 2 December 2014 в 12:38
поделиться

6 ответов

Обычно фабрики находятся в том же пакете, что и объекты, которые они создают; в конце концов, их цель - создать эти объекты. Обычно их нет в отдельной упаковке (на то нет причин). Кроме того, наличие фабрики в том же пакете, что и объекты, которые они создают, позволяет использовать видимость пакета.

23
ответ дан 1 December 2019 в 08:52
поделиться

почему бы и нет. сделайте это как можно ближе, если нет других возражений. собственно, почему бы не

public interface Toy
{
    static class Factory
    {
        public static final Toy make() { ... }
    }
}

Toy toy = Toy.Factory.make();

HA!

, но make () не должен статически зависеть от подклассов Toy, это было бы плохо. он может творить динамическую магию, в зависимости от стратегии вашей фабрики.

0
ответ дан 1 December 2019 в 08:52
поделиться

The whole point of a Factory is to have a configurable way to create implementation instances for interfaces. The convention to have the factory in the same package as the implementation classes it provides adds a completely unnecessary restriction you're unlikely to meet in the future. Also if the implementation returned is not the same across all contexts, it makes even less sense to have it in the same package.

For example, imagine a service lookup factory that is shared between the client and server part of an application, which returns a client side implementation (which resides in a client-only package) on the client, and a server side implementation (in a server-only package) when called from within the server's runtime.

Your factory may even be configurable (we do this by having a XML file which defines which implementation class to return for which interface), so the implementation classes can easily be switched, or different mappings can be used for different contexts. For example, when unit testing we use a configuration which returns mockup implementations for the interfaces (do be able to do unit tests that are not integration tests), and it would make no sense at all to require those mockup implementations to be in the same package as the factory, as they're part of the testing code rather than the runtime code.

My recommendation:

  • Don't add any package restrictions on the implmentation classes, as you don't know which implementations are used in the future, or in different contexts.
  • The interfaces may be in the same package, but this restriction is also unnecessary and only makes the configuration rigid.
  • Configurable factories (such as a service lookup) can be reused and shared across projects when the interface/implementation mapping isn't hardcoded. This point alone justifies having the factory separated from both the interfaces and the implementation classes.
5
ответ дан 1 December 2019 в 08:52
поделиться

Мне нравится помещать фабрику в пакет, для которого она создает объекты, здесь ключевое значение имеет именование, если оно четкое и прозрачное, это поможет усилиям по обслуживанию в дальнейшем.

Например, фабрика действий может быть структурирована как:

  • пакет org.program.actions
  • interface org.program.actions.Action
  • enum org.program. actions.ActionTypes
  • factory org.program.actions.ActionFactory (или .ActionManager )
  • классы реализации действий org.program.actions.LogAction и т. д.

Использование подобных шаблонов во всех проектах помогает участникам проекта находить классы, в которых они фактически находятся, в проектах, в которых они раньше не участвовали.

0
ответ дан 1 December 2019 в 08:52
поделиться

That wholly depends on the way you're intending to use said factories. Sometimes it makes sense to put a factory in its own package.

You might for example have an interface, foo.bar.ui.Interface. You want to have different implementations of that interface, one for AWT, one for Swing, one for the console, etc. Then it would be more appropriate to create a foo.bar.ui.swing.SwingInterfaceFactory that creates a foo.bar.ui.swing.SwingInterface. The factory for the foo.bar.ui.awt.AWTInterface would then reside in foo.bar.ui.awt.AWTInterfaceFactory.

Point is, there is no always-follow-this rule. Use whatever is appropriate for your problem.

0
ответ дан 1 December 2019 в 08:52
поделиться

единицей повторного использования является единица выпуска . Это означает, что не должно быть связи между пакетами, поскольку пакет обычно имеет самую низкую степень детализации выпуска. Когда вы организуете пакет, представьте, что вы говорите: «Вот все, что вам нужно для использования этих классов».

3
ответ дан 1 December 2019 в 08:52
поделиться
Другие вопросы по тегам:

Похожие вопросы: