How to make the constructor available only for the factory class?

Well, the question may not be crystal clear. Let me give you some details:

Say I have a factory class of a Shoe (CShoe) object called CFactory. CFactory is a singleton class that creates and stores all instinctive shoes using a simple hash map. It is then used through static methods to use the created objects.

Is there a way to force the CShoe constructor so that it can only be called by the factory? (in other words, make sure that shoe creation can only be done using the factory singleton class, not other classes)

+5
source share
6

Shoe a inner class ShoeFactory:

public class ShoeFactory {

    public static class Shoe {
        private String name;

        private Shoe() {
        }

        private Shoe(String name) {
            this.name = name;
        }
    }

    public static Shoe createShoe(String shoeName) {
        return new Shoe(shoeName);
    }
}

, , .... reflection:

public class SmellyShoe {

    public static void main(String[] args) {
        try {
            java.lang.reflect.Constructor c = Shoe.class.getDeclaredConstructors()[0];
            c.setAccessible(true);
            Shoe smelly = (Shoe)c.newInstance(null);
            // grr
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
+5

CShoe CShoe CFactory .

+4

, CShoe - .

+1

-, , . , , - , Shoe .

Just use the method staticto return the factory.

public final class Shoe implements Footwear {
    private static final FootwearFactory<Shoe,Something> FACTORY =
        new FootwearFactory<Shoe,Something>() {
            ...
            public Shoe get(Something value) {
                value = new Something(value);
                ...
                return new Show(value);
            }
        };
    private static FootwearFactory<Shoe,Something> getFactory() {
        return FACTORY;
    }

    private final Something value;
    private Shoe(Something value) {
        this.value = value;
    }
    ...
}
+1
source

Perhaps you can pass the factory object to the constructor?

public CShoe(CFactory factory)
{
    if (factory == null ||
          !factory.isValid()) // or whatever
    {
        throw new IllegalArgumentException();
    }
}
0
source

Could you just pass the instance of the caller as an argument to the static member of the shoe and do a check like "isInstanceOf" there, which calls the constructor if true?

0
source

All Articles