How to create class that provides implementations of some interfaces - java

There is some interfaces in my app and I want to create singleton class, that provides implementations of them. Like so:
public class Singleton{
//singleton's stuff
private Interface1 interface1Impl;
private Interface2 interface2Impl;
public Interface1 getInterface1(){
return interface1Impl;
}
public Interface2 getInterface2(){
return interface2Impl;
}
}
What I'm looking for - provide same interface implementation for each class in app. With this way everything works fine, but is it a good way to achieve this?

Yes, it looks much like a Factory (or maybe Service Locator is more suitable in your case).
Factory is almost always a better idea than a Singleton. For instance, a Factory can work as a Singleton when you need it (lazy initialization, caching), and you can alter this behavior when you need something else (for testing, thread safety, etc).

It looks to me like you could be implementing dependency injection, if that's the case Google Guice is a great library for you to use.

Related

Factory pattern design - clarifications

I've read the following article about Factory pattern here
Please refer only to the short section Class Registration - avoiding reflection.
This version is implementing reduced coupling between factory and concrete products without reflection.
So, I've tried to implement this version myself without success.
The reason is that static initializers of concrete product classes weren't launched, therefore they didn't registered in the hashmap, so calling the ProductFactory instance with createProduct method didn't succeed.
When I initialized some concrete classes in the client outside of the factory this led the static initializer to launch and the concrete class registered well. After that I called ProductFactory.getInstance().createProduct(productID)
and concrete class was finally created.
So the questions are:
Do this site example missing something?
How are the static initializers triggered in the given example?
Code that relevant for this example is(from site):
abstract class Product
{
public abstract Product createProduct();
...
}
class OneProduct extends Product
{
...
static
{
ProductFactory.instance().registerProduct("ID1", new OneProduct());
}
public OneProduct createProduct()
{
return new OneProduct();
}
...
}
class ProductFactory
{
public void registerProduct(String productID, Product p) {
m_RegisteredProducts.put(productID, p);
}
public Product createProduct(String productID){
return ((Product)m_RegisteredProducts.get(productID)).createProduct();
}
}
Yes, they're missing something, just like in the reflection example the class must be loaded before by the client or it won't get registered in the factory, which i don't think is a very clean approach, since the factory clients will have to load the class before asking for it, making the productId pretty much useless and coupling the clients with the particular product implementation.
I like what they (unfairly) call the noob implementation i think it's the most widely used and for good reasons, it's simpler and with it you can actually encapsulate and centralize the creation of objects without the client knowing anything about it but the id of the particular product (no direct class loading), the other implementations are useful when you're planning to let the ProductFactory clients to register new product implementations without having to modify code in the factory itself, but in most cases you'll find that modifying the factory when a new implementation comes in is not such a big deal.
So, to summarize, the noob implementation is not noobie at all, it's just simpler and suited to certain use cases. And in general, in cases like this, i don't think there are better or worse or noobie implementations, there are just different needs and use cases.
hint: It's cleaner and safer to use an enum instead of strings for productId, that is, of course, if you can modify the enum every time a new product implementation comes in.

Write own dependency injection

we are developing an application. The application will be deployed in a proprietary event processing engine. We are not supposed to use any api such as spring core for DI. There are not proprietary DI frameworks yet. So the idea is to write one and a simple one.
Can any one please provide some inputs.
My idea is to write a factory class which has static methods in it. The static methods will return instances of the classes we want. For now we only want a single instance. I am assuming the below kind of code
public final class MyFactory {
private static ClassA classA = new ClassA();
private static ClassB classB = new ClassB();
private MyFactory() {
throw new CustomException("Cannot create instance");
}
public static ClassA getClassAInstance() {
return classA;
}
public static ClassB getClassBInstance() {
return classB;
}
}
Later I will use it like this
public class SomeRandomClass {
private ClassA classA = MyFactory.getClassAInstance();
}
Other thing I see is I need not test ClassA and ClassB. Testing SomeRandomClass will cover ClassA and ClassB. Because static content is always loaded first. So while testing SomeRandomClass I always have ClassA instance in it. So writing a junit on some method in SomeRandomClass will invoke methods in ClassA. Is this good?
Is it the right way I am doing? Can I improve it even?
For starters, the factory API shouldn't reference the concrete class implementations directly like that. It kind of defeats the purpose. You won't be able to change the concrete classes without recompiling and you won't be able to do things like stubbing out interfaces for testing and development.
Then, assuming you want singletons (which is not how your example is written), you'll need to make sure your factory methods are thread safe in how they produce the singletons.
You should at a minimum have your factory return true singleton instances of interfaces. Then, you could implement some kind of configuration system and use the Java reflection API to determine which concrete classes should be created at runtime. This will also enable you to do things like stub out the interfaces for testing or development.
This isn't really DI. There's a lot more to it and it has benefits in readability/writability/configurability/maintainability that go far beyond what a factory can provide. I'm not sure why using Spring would be a problem in proprietary software. AFAIK Spring's license doesn't force code to be open source or free...

Dynamic dependency injection

I want to achieve DYNAMIC dependency injection. Does GUICE support this? If not could you recommend any other DI framework?
The implementation that should be used for injection via #Inject must be determined during runtime e.g. via interaction with the user.
Similar to these questiones:
http://www.panz.in/2008/12/dynamic-dependency-injection.html
http://www.panz.in/2008/12/dynamic-dependency-injection.html
Thank you
The implementation needs to vary based on input, at some point you're going to have to resolve the input into some kind of class.
If you want that mapping to live in Guice, then you're basically getting an implementation based on a parameter, which maps to the SO question I just answered here. You can write a small injectable class that takes the input and returns a fully-injected implementation.
If you already have that mapping and have (for instance) a class literal in a variable, then you can just inject an Injector directly and ask it for the implementation.
class YourClass {
#Inject Injector injector;
SomeInterface yourMethod(String input) {
Class<? extends SomeInterface> clazz = getClassLiteralFromInput(input);
return injector.getInstance(clazz);
}
Class<? extends SomeInterface> getClassLiteralFromInput(String input) {
// Implement this as needed.
return SomeInstance.class;
}
}
Note that while you can always inject an Injector, you should only do so when you really don't know what kind of implementation you need (like here). In general you should inject the SomeInstance itself, or a Provider<SomeInstance> if you want to delay the creation.
We had similar requirement once, so what we did was use a factory pattern and add all the implementations in factory class implementation using spring.
That ways, when on run time we would know which implementation to use, we would make a call to my factory to provide implementation class.
Also, anytime you have more implementations you could update spring configuration for factory class.
This may not be close to design you have in mind, but this solved the purpose for us.
Cheers !!

java create a wrapper interface for another interface

The problem I am facing is as below -
I am using a 3rd party library, say Editor, which has an interface , EditorActions, with methods -
create(), edit(), delete().
I do not want to expose, EditorActions 's methods in my implementation. So my interface will have methods like -
myCreate(), myEdit(), myDelete() which in turn should call the EditorActions methods.
EditorActions is only an interface, the implementation is internal to the library.
How do I link the 2 interfaces without implementing either of them?
thanks for all your help
You can do this by exposing the methods that you want people to use in an abstract class. And then force people to implement the specific methods that you want them to.
You can then use the methods from the EditorActions interface as well as the methods that you force you implementations to implement.
public abstract class AbstractEditorActions {
private EditorActions ea;
public AbstractEditorActions(EditorActions ea) {
this.ea = ea;
}
// In this method, you can use the methods
// from the interface and from this abstract class.
// Make the method final so people don't break
// the implementation.
public final void yourExposedMethod() {
// code
this.toImplement();
ea.doMethod();
}
protected abstract toImplement();
}
Assuming you obtain an instance of EditorActions from the library you could do this:
public class FooActions implements MyEditorActions, EditorActions{
private EditorActions internal;
public FooActions(EditorActions internal){
this.internal = internal;
}
#Override
public void create(){
internal.create();
}
#Override
public void myCreate(){
// do stuff
this.create();
}
}
What this does is wrap the instance of the library object with an object that implements the same interface as well as yours. Then, you just expose the object as whatever interface you want it to be.
EditorActions a1 = new FooActions(); // a1 only shows library methods
MyEditorActions a2 = a1; // now a2 only shows your methods
How do I link the 2 interfaces without implementing either of them?
You can't. You are trying to do automatic magic here. Don't do magic. You have to implement either one of them no matter what.
Or, you'll have to implement your own reflection plumbing (or AOP somehow) to create classes on the fly. The later is no trivial manner, and typically an overkill and a red-flag of over-engineering just to avoid implementing what amounts to be a plain-old delegate.
OTH, if you only wanted to "expose" a subset of the methods provided by a third party interface A (say, for example, only the getter methods), you could almost trivially create (by good old elbow grease or a reflection library) an interface B that only exposes that subset of methods you desire.
interface DirtyThirdPartyInterface
{
StupidCrap getSomeStupidCrap();
void setStupidCrap();
}
interface MySanitizedInterface
{
StupidCrap getSomeStupidCrap();
// the setter is not part of this interface
}
Then with, say, Spring AOP or something similar or one of the several reflection libraries out there, then you could auto-generate an implementation of MySanitizedInterface as an AOP interceptor that simply proxies the call to the getter (via reflection) to the getter in the 3rd party interface.
But again, that's a lot of crap (not to mention 3rd party library dependencies) to simply avoiding what amounts to be simple hand-coding. It is rare to find a real-world case that justifies all that plumbing malarkey. If I were to run into something like that, the first thing I would think is "red flag". YMMV of course.

Advice needed: static methods in JAVA interface

I have a class that is handling printing the various messages into the console, lets call this class ConsoleMessages.java. This class is public and abstract and all its methods are public and static.
I want to make an interface to this class (lets call it PrintMessages). I mean so, that ConsoleMessages.java will implement PrintMessages.
The thing is, JAVA doesn't support static methods in an interface.
What would you advise me to do?
Create the PrintMessages interface with the methods you desire.
Make ConsoleMessages a class that implements that interface. Change all methods from static to non static.
Enforce ConsoleMessages instantiation as a singleton. This can be achieved in many ways, either doing it yourself or using a Dependency Injection framework.
There is really no strong arguement against static methods in interface. Nothing bad would happen.
An interface can have static fields and static member classes though, therefore static methods can be attached through them, albeit with one extra indirection.
interface MyService
static public class Factory
static public MyService get(...)
return ...;
MyService service = MyService.Factory.get(args);
If you find yourself needing to define interfaces on a utility class then it may be time to revisit your design choices. Your ConsoleMessages class seems to have outgrown its initial use as a dumping ground for 'common utility functions'.
Short answer? Refactoring time.
Interfaces are there to specify methods for objects (which will then be implemented by some class). You have no objects here, thus you need no interface.
Static methods can only be called using the exact class name (or alternatively the name of some subclass), there is no point in using an interface to do this.
So, you have two options:
Throw your interface away and stay with the static methods.
Make all methods (or at least these which should be in the interface) non-static, and your implementing class non-abstract. To call them one then would need an object of the class (implementing this interface).

Categories