Nimrod Nimrod - 1 year ago 72
Java Question

Is this code implements 'Factory Pattern', factory methods, both or none?

Although this subject has been discussed many times, I still find myself get too confused with it.

I have this simple code sample:

public class FruitFactory {

public static Apple getApple() {
return new Apple();

public static Banana getBanana() {
return new Banana();

public static Orange getOrange() {
return new Orange();

  • Which
    type this code is? and is it a proper writing of
    factory methods

  • The factory pattern definition is: create an object without exposing the creation logic to the client

If I expose my client to some of the creation complexity like as the example below, is it a bad factory implementation?

public static Orange getOrange(String weight, String size,) {
return new Orange(weight, size);

amn amn
Answer Source

As it is said, a factory is merely an abstraction where object creation implementation is intentionally encapsulated behind the factory's public interface. A factory does not have to be a class, it does not have to be a package -- different languages achieve encapsulation of state and behavioral details differently (consider closures, for instance).

A function in a language that allows "top-level" functions, can be a factory as well:

public Orange growNewOrange(String weight, String size) {
    /// ...traditionally not callers concern.

If the factory hides creation code behind a way for you to use it without concerning yourself with said creation code for each created object, you already have a useful isolation (between getting new objects and that which manages them) that solves the problem the factory pattern was designed to solve.

There are factories that are designed to create and manage one kind of objects and then there are those that create and manage multiple kinds of objects. A fruit factory where you can specify the concrete class of fruit you want, still matches a valid factory pattern.

Categorizing factory implementations into "types" is done by various OOP authors, and may be useful for various good reasons, but this is not essential to be able to utilize the general idea to your advantage.

The immediately useful advice would be encapsulate creation code in a Java package or class, where specifying parameters of a created object is done on a per-object basis, while factory state controlling creation logic -- for instance size of reused object pool etc -- is set up during factory creation itself. Object pools are one of the examples of factory pattern at work.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download