This question already has answers here:
What does it mean to "program to an interface"?
(33 answers)
Closed 9 years ago.
I'm working on some JPA stuff and i'm a little confused with some of the start up code that you have to write.
EntityManagerFactory factory = Persistence.createEntityManagerFactory("sample");
EntityManager manager = factory.createEntityManager();
EntityTransaction transaction = manager.getTransaction();
Those three variables all have an interface as their type. How can we do things like
manager.persist()
transaction.commit()
etc if interfaces cannot be instantiated?
Interface cannot be instantiated but an interface reference can hold an object of any class implementing that interface. So in your case
EntityManagerFactory factory
is a reference of interface which is holding an object of the class implenting it , returned by :
Persistence.createEntityManagerFactory("sample");
and hence this statement becomes correct:
EntityManagerFactory factory = Persistence.createEntityManagerFactory("sample");
You are correct. Interfaces can not be instantiated but they provide a contract to call methods on objects that implement the interfaces.
So when you for example take a look at the EntityManager, factory.createEntityManager() is returning an object that implements the interface EntityManager. Interfaces make sure that the returned object provides certain required methods.
I think you are misunderstand what happened here.
EntityManager manager = factory.createEntityManager(); // here manager is only a reference You are getting that from EntityManagerFactory.
Now Factory class returns the manager type object. There is no instantiating for interfaces in Java
I think this is better seen than expained.
Examples:
public class AttackCommand implements Command {}...
public class DefendCommand implements Command {}...
....
let's say we wanted to add these to a common list of commands. Then you could add these to the list below.
(in a new class)
public ArrayList<Command> commands = new ArrayList();
public CommandManager() {
commands.add(new AttackCommand());
commands.add(new DefendCommand());
}
Now here is where that supposed reference comes in. What if we wanted to get a list of the command by name (pretending command has a getName method), or the last attacked target via AttackCommand (pretending it has a LastAttacked method)?.
public void printNames() {
for (Command cmd : commands) {
System.out.println(cmd.getName());
}
}
public Entity getLastAttackTarget() {
for (Command cmd : commands) {
if (cmd instanceof AttackCommand) {
return cmd.lastAttacked();
}
}
}
(I know that a map of the commands to just grab by name would be better, but for the sake of the example....)
In essence, it's a better general reference to all things that inherit the interface, but not the interface itself.
Related
I'm using generics to get my code reusable and to utilize dependency injection.
I have two Interfaces: DataParserImplementation and ObjectImplementation. I have classes that implement each: SalesRepbyId implements DataParserImpl (it parses the data into objects and puts those objects into collections). SalesRep implements Objectimpl (It is the object for a specific dataset).
I'm trying to get it so that I can select which kind of Objectimpl I use in my SalesRepbyId class so I can remove the coupling.
I know there is something called reflection that I've been told is the method I need to use. I also have heard about a "Factory Pattern" and a "Properties file" that allows me to do what I want to do. A lot of this is very confusing so please explain it like I'm five.
Here is the code with where it stops working:
EDIT: Revisions based on comments: I want to specify the type of DataObject (D) my class uses by passing it through the constructor via a common interface and using generic types. When I try and use it instead of a concrete implementing class, I get the error. I can't find anything about this error.
public class SalesRepbyId<D extends ObjectImplementation> implements DataParserImplementation<Map<String,D>> {
private FileParserImplementation<ArrayList<String[]>> FileParser;
private D dataObject;
public SalesRepbyId(FileParserImplementation<ArrayList<String[]>> FileParser,D d){
this.FileParser = FileParser;
this.dataObject = d;
}
#Override
public Map<String, D> Parse() {
try{
//reads the file and returns an array of string arrays
ArrayList<String[]> Salesrep_contactlist = FileParser.ReadFile;
//here it still says "Unknown Class." that's the problem
Map<String, dataObject> SalesrepByIdMap = new HashMap<>();
//I want to be able to put in any class that implements
//dataObject into this class and have it run the same way.
Summary of what I did
I Implemented the Factory Design pattern and created a properties file which allowed me to reflect in the class I wanted instead of trying to use a generic DataObject (or D) type.
Details of Solution
Reflecting the class using the properties file "config.properties" and then casting it to type Objectimplementation allowed me to use any class that implemented that interface (and was implemented in the Factory and set in the properties file). I then refactored all instances of D to type ObjectImplementation since the parent interface is the layer of abstraction needed here rather than a generic concrete class.
Why it didn't work the way I tried it in the question
the reason the generic D type doesn't work with reflection is because reflection uses a concrete classtype determined at runtime and the generic D type is specified before runtime. Thus I was trying to reflect in the classtype and its methods/instances without properly using reflection and the code was telling me that the classtype was unknown at the time I needed it.
Code example to compare to the Question code
Example of the working code:
public class SalesRepbyId implements
DataParserImplementation<Map<String,ObjectImplementation>> {
private FileParserImplementation<ArrayList<String[]>> FileParser;
//the Factory class that creates instances of the reflected class I wanted
private ObjectFactory Factory = new ObjectFactory();
public Map<String, ObjectImplementation> Parse() {
//the proeprties object which then loads properties from a file and reflects the classtype I want
Properties prop = new Properties();
//loading in the classtype and casting it to the subclass of ObjectImplementation that it actually is
prop.load(SalesRepbyId.class.getResourceAsStream("config.properties"));
Class<? extends ObjectImplementation> Classtouse = Class.forName(prop.getProperty("ObjectImplementation")).asSubclass(ObjectImplementation.class);
//construct instances of 'Classtouse' and parse the data into these dynamically typed objects
//return the map that holds these objects
}
Both Abstract Factory and Factory method patterns are creational design patterns which solves the object creation issues in different scenarios.
As per GOF Factory Method pattern
Define an interface for creating an object, but let the subclasses decide which class to instantiate. Factory method lets a class defer instantiation to subclass.
My Understanding :
Motive of the Client is to get a method present in the base Factory class get executed which is dependent upon an object whose concrete class is not known now (In such a case, either during providing the software to client, it will be defined, or it will be the client himself writing the concrete implementation, most likely in case of Framework). The not known (or likely to change) Product is provided an abstract type : IProduct, and setting a contract that in future any implementation for Product must implement this interface.
IProduct interface
package com.companyx;
public interface IProduct {
public void serve();
}
Factory class with 'a method' which needs to be executed
package com.companyx;
public abstract class Factory {
public abstract IProduct createProduct();
private void performCriticalJob(){
IProduct product = createProduct();
product.serve();
}
public void executeJob(){
//some code
performCriticalJob();
//some more code
}
}
Some concrete Product
package com.companyx;
class AppAProductFeatureX implements IProduct{
#Override
public void serve() {
//some code
}
}
Factory of the concrete Product
package com.companyx;
public class AppAFeatureXProductFactory extends Factory{
#Override
public IProduct createProduct() {
return new AppAProductFeatureX();
}
}
Client code
package com.clientcompany;
import com.companyx.AppAFeatureXProductFactory;
import com.companyx.Factory;
public class Client {
public static void main(String[] args) {
Factory fact = new AppAFeatureXProductFactory();
fact.executeJob();
}
}
As per GOF Abstract Factory pattern
Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
My Understanding
The client is interested in the products, here this pattern helps in providing the product by hiding the concrete product classes behind factory classes.
Product type wanted by the client
package com.companyb;
public interface IProductA {
public void performAJob();
}
Implementation of the product
package com.companyb;
//can be named better, but lets go with this name for this time
public class ProductAVersion1 implements IProductA{
#Override
public void performAJob() {
// some code
}
}
Factory interface, (It can be also an abstract class)
package com.companyb;
public interface IFactory {
public IProductA createProduct();
}
Concrete implementation of Factory o create ProductA
package com.companyb;
public class FactoryA implements IFactory{
#Override
public IProductA createProduct() {
return new ProductAVersion1(); // concrete class of product is hidden
}
}
Client Code
package com.clientcompany.productprovider;
import com.companyb.IFactory;
import com.companyb.IProductA;
public class SomeClientClass {
private IFactory factory;
private IProductA product;
public void doSomeJobWithProductA() {
// some code
product.performAJob();
//someCode();
}
public void setFactory(IFactory factory) {
this.factory = factory;
this.product = factory.createProduct();
}
}
package com.clientcompany.productprovider;
import com.companyb.FactoryA;
public class SomeOtherClientCode {
public static void main(String[] args) {
SomeClientClass someClientClass = new SomeClientClass();
someClientClass.setFactory(new FactoryA());
someClientClass.doSomeJobWithProductA();
}
}
Q1 : Is the family of related product necessary in Abstract Factory patter , won't this pattern still be relevant if only one kind of product (like above) is there with various sub types but not various related types?
Q2 Is my understanding above correct ?
Q3 Above brings another doubt in my mind : Is Factory method more suitable for frameworks (where client can give the implementation of products) and just like template method pattern, factory invokes the createProduct() concrete implementation form the user provided Concrete Factory implementation ?
Also similarly is Abstract factory more fits for Library development, where concrete product classes (likely to vary) are hidden behind more stable Factory classes ?
I am having real difficulty in getting into your shoes. But I am quite interested in this subject so I will give a try. Involved here are concepts like library, framework, factory method, abstract factory and product family etc.
First, the library vs framework has really nothing to do with factory, abstract factory or any pattern for that matter. Library vs framework debate is not from implementational perspective where the patterns play. For example JUnit is a framework which comes with a rich assertion library. So should junit prefer one pattern over other for its internal implementation? Java itself is a framework which comes with a JCL library. Dot Net which is similar to java even calls itself a framework, and contains BCL library. So no more framework vs library debate in implementational context.
So the question boils down to which pattern should you use? It is not about the difference, which is clear, but about which one to use in which scenario. In this context, the Client Code is all code which may call the one which you are typing right now. It does not matter whether some code is written by you or someone else, in same or different jar, from same or different organization. From perspective of one code fragment, any other code (even in different method of the same class) is client code if that code has a potential to call the code which you are typing right now.
While typing any code (irrespective of framework or library status) sometimes we need to obtain instances of some object. May be we need a BufferedReader. If at compile time we are absolute sure about the concrete class of the object, KISS it and go with newing.
We may not know the concrete class of an instance. Now question aries whether the client code has this information? If the client code knows about the actual concrete class, but I do not know then we use the FactoryMethod pattern. The code I am typing will ask for an instance of a factory object in (say) its argument list. The client code knowing the actual concrete class, will supply a factory object which will do the creation. Example of this case is seen in JDBC like we want to process an sql statement. At compile time we do not know whether we should instantiate a mysql.JDBC4PreparedStatement or a microsoft.SQLServerStatement. It depends on connection string and that depends on end user. So we get hold of a Connection instance and ask it to createStatement(). See, we are delegating the construction of an object of type sql.Statement to a subclass of sql.Connection. Here the conn instance is the factory object. How we get hold of the factory is immaterial, just that we got it from client code.
If we need an instance of a Process object and at compile time we do not know whether it will be a Win32Process or a UnixProcess, we delegate the responsibility of its creation to ProcessBuilder which is builder pattern related to factory pattern. Same goes for jdbc ConnectionManager.
In case when there are many different classes not related by inheritance but by family we may use AbstractFactory. For example take jdbc's dot net counterpart DbProviderFactory. My code needs instances of Connection, Command, DataReader etc which are not related by inheritance but by family of MySql or SqlServer. So we get hold of an instance of a subclass of DbProviderFactory. May be it is a MySqlProviderFactory or a SqlProviderFactory that depends on runtime and client code. Once we have that factory, we can do CreateCommand(), CreateConnection() etc.
Hope this helps you choose between factory pattern and abstract factory pattern.
In my understanding:
A1: The family of product does not need to be necessarily related, as shown on an example diagram, only a Client is needed that has knowledge of the type of products. The relation is mostly natural as you probably don't want the same Client to create 2 unrelated objects, e.g., it would look strange if you have an "AbstractPizzaFactory" that creates Pizza and Cars, no?
A2: Technically you can provide a default factory method in the Factory pattern, so that you can still create (defaults) new Objects without always subclassing it.
A3: I would agree with you on this point, although creating a Library or a Framework is never black and white.
Abstract Factory can be seen as collection of the Factory Methods.
For better understanding examples from real life can help:
Factory Method - plasticine/mold
Abstract Factory - cards factory
I am clear with polymorphism and inheritance concept of oop, but I am in a situation where I need to know the implementing class. For example:
public CommonReadRepository<?> getReadRepository(String tableName) {
if (tableName == null)
return null;
switch (tableName) {
case "order":
return orderRepository;
...
}
return null;
}
The interface orderRepository extends CommonReadRepository, and because of my requirement, I need to access a function defined in orderRepository.
CommonReadRepository<?> repository=getReadRepository("order");
Is there any way to check back the implementing (child) class or interface of CommonReadRepository?
Of course, I can always do something like this:
if(tableName=="order")
return (OrderRepository)CommonReadRepository<?>;
I tried to debug getReadRepository("order"), but it gives me an instance of JdkDynamicAopProxy, and I am not sure how it works.
if(interface is instanceof xyz class)
i do not want to use it because i have 100 of classes and i want to keep it as a last resort... or in other words
i don't know about xyz class
Thanks
Following is one way to check if the returned Object is an instance of the specified class:
CommonReadRepository<?> repository=getReadRepository("order");
if(repository instanceof WhatEverSubclass) {
// do something
}
But using this approach is not how OOP is supposed to be done. If your classes all implement the same Interface, why don't you define a common method, that's then used in all the subclasses, but implement it differently every time.
I think, what you try to do is not getting you anywhere.
You can find all available classes inheriting an interface using the reflections tool (https://github.com/ronmamo/reflections). I used it for a dependency injector and it works very reliable.
Yet, why don't you just use the instanceof operator to make sure the object is of the right type:
if( repository instanceof OrderRepository) return (OrderRepository)repository;
But still, this won't change the return type of your function and you need to inspect the type of the returned value again outside of your function.
Update: If this happens for hundreds of objects, you could change the getRepository method to return a type you give as parameter: <T> getRepository(String name, Class<T> expectedType)
This will allow you OrderRepository o = getRepository("order", OrderRepository.class);
Is Javascript-like prototyping anyhow achievable, even using Reflection? Can I wrap my object inside another one, just to extend its functionality with one or two more methods, without wiring all its original nonprivate methods to the wrapper class, or extends is all I get?
If you are looking for extension methods, you could try Xtend. Xtend is language that compiles to java code and eliminates boilerplate code.
The following text is stolen from the Xtend Docs for extensions:
By adding the extension keyword to a field, a local variable or a parameter declaration, its instance methods become extension methods.
Imagine you want to have some layer specific functionality on a class Person. Let us say you are in a servlet-like class and want to persist a Person using some persistence mechanism. Let us assume Person implements a common interface Entity. You could have the following interface
interface EntityPersistence {
public save(Entity e);
public update(Entity e);
public delete(Entity e);
}
And if you have obtained an instance of that type (through a factory or dependency injection or what ever) like this:
class MyServlet {
extension EntityPersistence ep = Factory.get(typeof(EntityPersistence))
...
}
You are able to save, update and delete any entity like this:
val Person person = ...
person.save // calls ep.save(person)
person.name = 'Horst'
person.update // calls ep.update(person)
person.delete // calls ep.delete(person)
I don't think you can do this in Java. You can though in Groovy, using metaclasses
String.metaClass.world = {
return delegate + " world!"
}
println "Hello".world()
I better explain the question with an example.
I have an Interface Model which can be used to access data.
There can be different implementations of Model which can represent the data in various format say XMl , txt format etc. Model is not concerned with the formats.
Lets say one such implementation is myxmlModel.
Now i want to force myxmlModel and every other implementation of Model to follow Singleton Pattern.The usual way is to make myxmlModels constructor private and provide a static factory method to return an instance of myModel class.But the problem is interface cannot have static method definitions and a result i cannot enforce a particular Factory method definition on all implementation of Model. So one implementation may end with providing getObject() and other may have getNewModel()..
One work around is to allow package access to myxmlModel's constructor and create a Factory class which creates the myxmlModel object and cache it for further use.
I was wondering if there is a better way to achieve the same functionality .
Make a factory that returns
instances of your interface, Model.
Make all concrete implementations of the model package-private classes
in the same package as your factory.
If your model is to be a singleton, and you are using java
5+, use enum instead of traditional
singleton, as it is safer.
public enum MyXMLModel{
INSTANCE();
//rest of class
};
EDIT:
Another possibility is to create delegate classes that do all the work and then use an enum to provide all of the Model Options.
for instance:
class MyXMLModelDelegate implements Model {
public void foo() { /*does foo*/}
...
}
class MyJSONModelDelegate implements Model {
public void foo() { /*does foo*/ }
...
}
public enum Models {
XML(new MyXMLModelDelgate()),
JSON(new MyJSONModelDelegate());
private Model delegate;
public Models(Model delegate) { this.delegate=delegate; }
public void foo() { delegate.foo(); }
}
You can use reflection. Something like this:
public interface Model {
class Singleton {
public static Model instance(Class<? extends Model> modelClass) {
try {
return (Model)modelClass.getField("instance").get(null);
} catch (blah-blah) {
blah-blah
}
}
}
public class XmlModel implements Model {
private static final Model instance = new XmlModel();
private XmlModel() {
}
}
usage:
Model.Singleton.instance(XmlModel.class)
Actually, I don't like this code much :). First, it uses reflection - very slow, second - there are possibilities of runtime errors in case of wrong definitions of classes.
Can you refactor the interface to be an abstract class? This will allow you to force a particular factory method down to all implementing classes.
I used to ask myself the same question. And I proposed the same answer ;-)
Now I normally drop the "forcing" behavior, I rely on documentation.
I found no case where the Singleton aspect was so compelling that it needed to be enforced by all means.
It is just a "best-practice" for the project.
I usually use Spring to instanciate such an object,
and it is the Spring configuration that makes it a Singleton.
Safe, and so easy ... plus additionnal Spring advantages (such as Proxying, substituing a different object once to make some tests etc...)
This is more an answer to your comment/clarification to kts's answer. Is it so, that the real problem is not using the Singleton pattern but instead defining an eclipse (equinox) extension point schema that allows contributing a singleton?
I think, this can't be done, because everytime you call IConfigurationElement.createExecutableExtension you create a new instance. This is quite incompatible with your singleton requirement. And therefore you need the public default constructor so that everybody can create instances.
Unless you can change the extension point definition so that plugins contribute a ModelFactory rather than a model, like
public interface ModelFactory {
public Model getModelInstance();
}
So the extension user will instantiate a ModelFactory and use it to obtain the singleton.
If I guessed wrong, leave a comment and I delete the answer ;)