I have a situation where my application can be in exactly one of a several "modes". Since these are discrete values I'd like to model them using an enum type.
With each state my application needs to perform a slightly different functionality, which I'd like to model using the plug-in pattern. I've defined an interface and provided a few implementations.
I'd now like my enumeration to return the plug-in that is appropriate for it's state. I'd like to do the following:
public enum Mode {
ONE {
#Override
public MyType get() { return factory.getFirst(); }
},
TWO {
#Override
public MyType get() { return factory.getSecond(); }
};
#Autowired private MyTypeFactory factory;
public abstract MyType get();
// Other methods removed for clarity
}
However this isn't going to work. This is because I'm using spring injection to add the plug-in factory to the enum (enum constants are static and spring injected variables are instance variables so I'll get a compilation error)
I can't create the MyType instances directly from the enum because they will require dependency injection
How do I get around this?
This probably isn't the best solution (and I'd love to see something better suggested), but this is what I did in the end:
Modify the Factory so it reads:
public class MyTypeFactory {
private static MyTypeFactory me;
#PostConstruct
public void initialise() {
if (me == null) {
me = this;
}
}
public static MyTypeFactory getInstance() {
return me;
}
// The same code as before - getFirst(), getSecond() etc
}
So, a (singleton) spring managed bean that looks a bit like an old GOF singleton! The important difference is that there is a publicly accessible default (no argument) constructor
I can then modify my enum to read:
public enum Mode {
ONE {
#Override
public MyType get() { Factory.getInstance().getFirst(); }
},
TWO {
#Override
public MyType get() { Factory.getInstance().getSecond(); }
};
public abstract MyType get();
// Other methods removed for clarity
}
The enum can get access the factory via the static getInstance method when get() is called
Related
I'm integrating a servlet application with Guice (could be Spring, I choose Guice just because I worked with it). And this application use constant-specific method extensively (thousands of enums). From service, it determine the action to call:
ActionEnum act = ActionEnum.valueof("Action from context");
act.perform();
The enum action looks like this:
public enum ActionEnum {
ACTION1 { perform() {}},
ACTION2 { perform() {}};
abstract void perform();
}
Is there any way to inject something in to the enum class by Guice (or Spring)? eg:
public enum ActionEnum {
ACTION1 {
#Inject
SomeClass case1ToBeUsedByAction1;
void perform() {
case1ToBeUsedByAction1.doSomething();
case2ToBeUsedByActionN.doSomething();
}
},
ACTION2 { void perform() { case2ToBeUsedByActionN.doSomething(); }};
abstract void perform();
#Inject SomeClass case2ToBeUsedByActionN;
}
Or how do I change the current code base to enable injection?
You could add the class as an enum value like this:
public enum TestType {
TEST_TYPE_1("TEST-1", Test1.class),
TEST_TYPE_2("TEST-2", Test2.class),
TEST_TYPE_3("TEST-3", Test3.class),
TEST_TYPE_4("TEST-4", Test4.class),
TEST_TYPE_5("TEST-5", Test5.class);
private final String testType;
private final Class<? extends TestIF> tester;
private <T extends TestIF> TestType(String testType, Class<? extends TestIF> tester) {
this.testType = testType;
this.tester = (Class<tester.TestIF>) tester;
}
public String toString() {
return this.testType;
}
public Class<? extends TestIF> tester() {
return this.tester;
}
and then implement the TestIF for each class and execute the injected classes like this:
TestIF tester = Guice.createInjector().getInstance(testType.tester());
tester.perform();
Instances of Java enum are created at compile-time. Whereas instance creation and management by guice is dynamically executed during runtime.
Note that an enum type cannot have a public constructor, which consolidates the fact that dynamic creation of an enum type instance during runtime would not be possible.
Or how do I change the current code base to enable injection?
-- There's nothing you can do about the issue other than use a regular class type. Guice cannot do an injection into your enum class, since the injection is possible during runtime when enum type instances would have been created already.
I was reading Effective java text book. First item is about using static factory methods instead of public constructor. My doubt is that if i am specifying an Interface how can i specify a static factory method in the Interface ? Because java does not support static methods inside interface. The text book specifies about creating a non-instantiable class containing the public static factory methods. But how can those method access the private constructor of the implementation class?
The text book says if you are defining an Interface Type , create a non-instantiable class Types and include the static factory methods in that class. But how can a method defined in the Types class access the private constructor of a concrete implementation of Interface Type
EDIT:- Below sentence is quoted from the text book. Please explain me its meaning
"Interfaces can’t have static methods, so by convention, static factory methods for an interface named Type are put in a noninstantiable class (Item 4) named Types "
EDIT:- taken from Effective Java By Joshua Bloch: Item1 - Static Factory Method
public interface Foo{ //interface without plural 's' (question 1)
public void bar();
}
public abstract class Foos(){ // abstract factory with plural 's' (question 1)
public static Foo createFoo(){
return new MyFoo();
}
private class MyFoo implements Foo{ // a non visible implementation (question 2)
public void bar(){}
}
}
My question is that how can the static method createFoo() calls the private constructor of MyFoo
You can define the factory as returning the Interface but internally it creates a concrete class.
For example:
public Interface I { }
private class Impl implements I {
}
I buildI() {
return new Impl();
}
The trick is to create the implementations with package private (or even if they are inner classes private) constructors and then only the factory can build them.
The power of this method is that the factory can build the appropriate implementation depending on the requirements and that all happens invisibly to the user. For example when you create an EnumSet using the factory there are multiple internal implementations depending on how many entries there are in the Enum that the EnumSet is being built for. A super-fast version using bitfields on a long for Enums with less than 64 entries, a slower version for longer enumerations.
To specify the interface for a factory all you need to do is:
public interface Factory {
I buildI();
}
Now people can call you with setFactory(new FactoryImpl()); you can then call factory.buildI() and their code then returns the concrete implementation.
You can take this a step further and use Generics:
public interface GenericFactory<T> {
T buildInstance();
}
And then your setFactory becomes:
public void setFactory(GenericFactory<I> factory);
To create a factory they do:
public class FactoryImpl implements GenericFactory<I> {
#override
I buildInstance() {
return new impl();
}
}
But now you can use that same factory class for absolutely anything that needs a factory, just change the generics requirement.
The reason it can call the private constructor is very simple - it's declared in the same class!
Inside one Java file you can create the class with the private constructor. You then define the static method inside the class and even though it is static it still has the privileges required to access the constructor.
If the factory and implementation are in separate classes then they will be placed in the same package and the method made package private instead of private.
Java 8 finally allows interfaces to have static methods.
See this archived copy of the TechEmpower blog for details.
One way to think about this is with the package encapsulation in mind. Consider this Java 9+ code:
public interface Engine {
void start();
static Engine getEngine(String type) {
switch (type) {
case "combustion":
return new CombustionEngine();
case "electric":
return new ElectricEngine();
default:
throw new IllegalArgumentException("Unknown engine type : " + type);
}
}
}
class CombustionEngine implements Engine {
CombustionEngine() {
}
#Override
public void start() {
// injecting fuel and igniting it to create combustion...
}
}
class ElectricEngine implements Engine {
ElectricEngine() {
}
#Override
public void start() {
// electric current from battery flowing through coil in magnetic field...
}
}
Note that constructors in implementations are package-private so the caller from a different package can't instantiate implementation directly and should use the factory method.
Having the factory method in the interface
has no need for a dedicated EngineFactory class (the traditional implementation of Factory method design pattern)
reminds to Program to interface, not implementation
If needed, there is also a way to create implementation instances as singletons, which improves memory footprint :
public interface Engine {
enum EngineType {
COMBUSTION,
ELECTRIC;
private static EnumMap<EngineType, Engine> MAP = new EnumMap<>(EngineType.class);
static {
MAP.put(COMBUSTION, new CombustionEngine());
MAP.put(ELECTRIC, new ElectricEngine());
}
}
void start();
static Engine getEngine(EngineType type) {
return EngineType.MAP.get(type);
}
}
You cannot define a factory method in an interface, but you cannot have a constructor in an interface either: Interfaces cannot be instantiated. The point is to use a factory method instead of a constructor in the classes implementing the interface, not in the interface itself.
It talks about creating object via static factory method in the implementation not the interface
public Interface MyInterface {
public void myFunction();
}
public class MyClass implements MyInterface {
// constructor is made private
private MyClass() {}
// Use this to create object instead use static factory
public static MyClass getInstance() {
return new MyClass();
}
public void myFunction(){
// your implementation
}
}
A previous post also talks about static factory method.. What are static factory methods?
Apart from the book I also find the undermentioned link a good read
http://www.javacodegeeks.com/2013/01/static-factory-methods-vs-traditional-constructors.html
I have a following problem I want to solve ellegantly:
public interface IMyclass
{
}
public class A
{
public void Init(IMyclass class){?}
public IMyclass CreateMyClass(){?}
}
At the start of the system I want to define dynamic type of IMyClass by using Init() and during the run of the system i would like to create new instances of the type I defined at init.
Notes:
1. IMyclass must be interface
2. The dynamic type of IMyclass known only at init (i have no constructor after :) )
3. I could do it using a reflection or definition method clone at IMyclass is there any better solutions?
Thank you.
You could pass a provider into class A
public class A
{
IMyClassProvider _provider;
public void Init(IMyClassProvider provider)
{
_provider = provider;
}
public IMyclass CreateMyClass()
{
return _provider.Create();
}
}
Or maybe with a constructor delegate
public class A
{
Func<IMyclass> _ctor;
public void Init(Func<IMyclass> ctor)
{
_ctor = ctor;
}
public IMyclass CreateMyClass()
{
return _ctor();
}
}
Note that both of these examples will blow up if Init has not been called before CreateMyClass, you would need some checking or better is doing your init in the constructor.
Have I understood the question correctly?
This is a kind of dependency injection, you should read:
http://en.wikipedia.org/wiki/Dependency_injection
http://www.martinfowler.com/articles/injection.html#FormsOfDependencyInjection
Basically, you have a class A that is populated with factories (or providers) at initialization. Then you use A instead of calling new.
A quick example:
interface Provider<V> {
V instance(Object... args);
}
class Dispatch {
// you can make a singleton out of this class
Map<Class, Provider> map;
<T> void register(Class<T> cl, Provider<? extends T> p) {
// you can also bind to superclasses of cl
map.put(cl, p);
}
<T, I extends T> void register(Class<T> cl, final Class<I> impl) {
register(cl, new Provider<I>() {
I instance(Object... args) {
// this class should be refactored and put in a separate file
// a constructor with arguments could be found based on types of args values
// moreover, exceptions should be handled
return impl.newInstace();
}
});
}
<T> T instance(Class<T> cl, Object... args) {
return map.get(cl).instance(args);
}
}
// usage
interface MyIf { ... }
class MyIfImpl implements MyIf { ... }
Dispatch d = new Dispatch();
d.register(MyIf.class, new Provider<MyIf>() {
MyIf instance(Object... args) {
return new MyIfImpl();
}
});
// or just
d.register(MyIf.class, MyIfImpl.class);
MyIf i = d.instance(MyIf.class);
Edit:
added register(Class, Class)
If you just want to instantiate the same class in CreateMyClass() without further configuration you can use reflection.
public class A
{
private Class prototype;
public void Init(IMyClass object) {
this.prototype = object.getClass();
}
public IMyClass CreateMyClass() {
return prototype.newInstance();
}
}
I suspect you want more than this, and if so you'll need to explain how you want to use this. You may be looking for the Builder or Factory patterns.
You'll need Reflection at some point due to visibility. If you can accept Reflection once up-front and not have to use it again, that would probably be ideal, yes?
You could put a getInstance() method on a hidden interface (located in the same package as IMyClass, MyClassImpl, and A, but not ClientOfA), and then pass a prototype of MyClassImpl to A.init().
// -- You wish you would have thought of the word prototypeable! ...maybe?
interface IMyClassPrototypeable extends IMyClass
{
public IMyClass getInstance();
}
class MyClassImpl implements IMyClassPrototypeable // -- and IMyClass by extension.
{
// -- Still not visible outside this package.
public IMyClass getInstance()
{
return new MyClassImpl();
}
}
class A
{
private IMyClassPrototypeable prototype;
// -- This method is package-private.
void init( IMyClassPrototypeable prototype )
{
this.prototype = prototype;
}
public IMyClass createMyClass()
{
return prototype.getInstance();
}
}
This solution would require Reflection to create the prototype instance of MyClassImpl, which could be done via Spring (or some other form of dependency injection). It uses the Prototype pattern, the Factory-method pattern, and readily supports the Singleton/Pool pattern, but remember that more design patterns used is not always better. In fact, it can make the design (and code) more complex and more difficult for a beginner to understand.
For the record, the only reason I would even think about advocating this solution is because it takes the reflection hit once, up front, rather than every time createMyClass() is called, which the original poster indicated he/she would be doing frequently.
What I mean is:
public class SomeBackingBean {
protected String someString;
public void setSomeString (String str) {
this.someString = str;
}
public String getSomeString {
return someString;
}
}
It was just a general case for a general answer.
Now second example:
public abstract class AbstractBean<T extends EntityInterface> {
protected T entity;
public void setEntity (T t) {
this.entity = t;
}
public void getEntity () {
return entity;
}
protected ReturnType calculateSomethingCommon () {
//use entity (knowing that it implements EntityInterface)
//to implement some common for all subclasses logic
}
}
public class ConcreteBean extends AbstractBean<ConcreteEntity> {
...
//and here we can write only specific for this bean methods
...
}
Is second example an example of bad practice too?
In general, protected variables violate object oriented principles. You're giving other objects direct access to member variables. By doing so, you form tighter coupling and it makes it harder to change the variable, since other objects are directly using it. It also means you can't do things like validate when it's set, add logging around getters/setters, etc.
If, for example, you have a PropertyChangeListener registered to properties for a bean, any registered listeners might not be notified if a protected property is changed directly by a sub-class.
What would be the practical side of the ability to define a class within an interface in Java:
interface IFoo
{
class Bar
{
void foobar ()
{
System.out.println("foobaring...");
}
}
}
I can think of another usage than those linked by Eric P: defining a default/no-op implementation of the interface.
./alex
interface IEmployee
{
void workHard ();
void procrastinate ();
class DefaultEmployee implements IEmployee
{
void workHard () { procrastinate(); };
void procrastinate () {};
}
}
Yet another sample — implementation of Null Object Pattern:
interface IFoo
{
void doFoo();
IFoo NULL_FOO = new NullFoo();
final class NullFoo implements IFoo
{
public void doFoo () {};
private NullFoo () {};
}
}
...
IFoo foo = IFoo.NULL_FOO;
...
bar.addFooListener (foo);
...
I think this page explains one example pretty well. You would use it to tightly bind a certain type to an interface.
Shamelessly ripped off from the above link:
interface employee{
class Role{
public String rolename;
public int roleId;
}
Role getRole();
// other methods
}
In the above interface you are binding the Role type strongly to the employee interface(employee.Role).
One use (for better or worse) would be as a workaround for the fact that Java doesn't support static methods in interfaces.
interface Foo {
int[] getData();
class _ {
static int sum(Foo foo) {
int sum = 0;
for(int i: foo.getData()) {
sum += i;
}
return sum;
}
}
}
Then you'd call it with:
int sum = Foo._.sum(myFoo);
I can say without hesitation that I've never done that. I can't think of a reason why you would either. Classes nested within classes? Sure, lots of reasons to do that. In those cases I tend to consider those inner classes to be an implementation detail. Obviously an interface has no implementation details.
One place this idiom is used heavily is in XMLBeans. The purpose of that project is to take an XML Schema and generate a set of Java classes that you can use bidirectionally to work with XML documents corresponding to the schema. So, it lets you parse XML into xml beans or create the xml beans and output to xml.
In general, most of the xml schema types are mapped to a Java interface. That interface has within it a Factory that is used to generate instances of that interface in the default implementation:
public interface Foo extends XmlObject {
public boolean getBar();
public boolean isSetBar();
public void setBar(boolean bar);
public static final SchemaType type = ...
public static final class Factory {
public static Foo newInstance() {
return (Foo)XmlBeans.getContextTypeLoader().newInstance(Foo.type, null);
}
// other factory and parsing methods
}
}
When I first encountered this it seemed wrong to bind all this implementation gunk into the interface definition. However, I actually grew to like it as it let everything get defined in terms of interfaces but have a uniform way to get instances of the interface (as opposed to having another external factory / builder class).
I picked it up for classes where this made sense (particularly those where I had a great deal of control over the interface/impls) and found it to be fairly clean.
I guess you could define a class that is used as the return type or parameter type for methods within the interface. Doesn't seem particularly useful. You might as well just define the class separately. The only possible advantage is that it declares the class as "belonging" to the interface in some sense.
Google Web Toolkit uses such classes to bind 'normal' interface to asynchronous call interface:
public interface LoginService extends RemoteService {
/**
* Utility/Convenience class.
* Use LoginService.App.getInstance() to access static instance of LoginServiceAsync
*/
class App {
public static synchronized LoginServiceAsync getInstance() {
...
}
}
}
With a static class inside an interface you have the possibility to shorten a common programming fragment: Checking if an object is an instance of an interface, and if so calling a method of this interface. Look at this example:
public interface Printable {
void print();
public static class Caller {
public static void print(Object mightBePrintable) {
if (mightBePrintable instanceof Printable) {
((Printable) mightBePrintable).print();
}
}
}
}
Now instead of doing this:
void genericPrintMethod(Object obj) {
if (obj instanceof Printable) {
((Printable) obj).print();
}
}
You can write:
void genericPrintMethod(Object obj) {
Printable.Caller.print(obj);
}
Doing this seems to have "Bad design decision" written all over it.
I would urge caution whenever it seems like a good idea to create a non-private nested class. You are almost certainly better off going straight for an outer class. But if you are going to create a public nested class, it doesn't seem any more strange to put it in an interface than a class. The abstractness of the outer class is not necessarily related to the abstractness of a nested class.
This approach can be used to define many classes in the same file. This has worked well for me in the past where I have many simple implementations of an interface. However, if I were to do this again, I would use an enum which implements an interface which would have been a more elegant solution.