Looking for some sort of pattern - java

I have a library project which contains an abstract class, let's say ClassA. In the project that uses that library project, I have ClassB that extends ClassA.
Now here's my problem. In the library project I want to use an instance of the implemented ClassB, but I have no idea how to retrieve that instance. Is there any pattern or other ideas for this?
Here's a simple diagram of the situation.
Edit
The reason I'm asking is that I'm creating multiple applications, which only have different methods in ClassB. Therefore I'm creating a library that all of these applications can use, only having to extend ClassA. These applications are separate projects, using the library.

What you're looking for is something like the Abstract Factory pattern. The application code (the code that calls into the library) would, at some point, need to pass in a Factory class that would be used by the library to create instances of ClassA objects. In your case, the Factory class would generate instances of ClassB.
Depending on the design and functionality of the classes, it's likely that ClassA should be redesigned as an interface, or at least as an abstract class, as part of this refactoring.
EDIT:
Here's an untested pseudo example:
This code would be in the library
class INeedAFactory {
public Interface MyFactory {
public ClassA makeClassAInstance();
}
private MyFactory m_factory;
public registerFactory(MyFactory factory) {
m_factory = factory;
}
private ClassA makeClassAInstance() {
// m_factory had better not be null!
return m_factory.makeClassAInstance();
}
private void ClassAConsumer() {
ClassA classA = makeClassAInstance();
// ... etc. ...
}
}
This code would be in the application:
class LibraryPatron {
class MakeClassB implements INeedAFactory.MyFactory {
public ClassA makeClassAInstance() {
return new ClassB();
}
}
public LibraryPatron() {
INeedAFactory libraryObject = new INeedAFactory();
libraryObject.registerFactory(new MakeClassB());
// ... etc...
}
}

If your library needs to use ClassB, then ClassB should be part of your library. Your library shouldn't need to know about classes in projects which use it.
If your library just needs a ClassA, and you've got a ClassB, you can cast your object to a ClassA before you pass it in, like this:
ClassB b = new ClassB();
ClassA a = (ClassA)b;
// pass a into your library

Move class B into the same library as class A. Your project already depends on the library so it will still be able to reference class B but class B will also now be available to other classes within the library.

It isn't really clear, but as I understand it if you want to get an instance of the ClassB you just need to do a new ClassB()...

So you're writing an abstract class and you want it to be able to get a hold of all objects of unknown sub-classes of that class? It sounds to me like you're wanting an Aspect-Oriented management like AspectJ or PicoContainer.

I feel sick when I write this, because your design is flawed, but you asked how you would do it....so here it goes:
Class<?> bClass = Thread.currentThread().getContextClassLoader().loadClass("com.foo.ClassB");
Then you can do something like:
if (object.getClass() == bClass) { ... }
I would seriously recommend coming up with a better solution however. Try writing your code in one project then re-factor out common things that can make up your "library".

Related

Java Application return super class when initialized

Nowadays we are on writing some core application that is all other application will be relying on. Without further due let me explain the logic with some codes,
We used to have a single java file that was 1000+ lines long and each application was having it as class inside, so when there was a change, each application had to edit the java file inside of it or simply fix one and copy to all. This is hard to implement as much as it is hard to maintain. Then we end-up with creating this as a separate application that is divided to smaller part, which is easy to maintain and also a core maybe a dependency to other application so we fix in one place and all other code applications are fixed too.
I've been thinking for a some great structure for this for a while want to use a builder patter for this as below
TheCore theCore = new TheCore().Builder()
.setSomething("params")
.setSomethingElse(true)
.build();
The problem arises now. Like so, I initialized the object but now I'm having access to that objects public class only. This application actually will have many small classes that has public functions that I don't want them to be static methods that can be called everytime. Instead I want those methods to be called only if TheCore class is initilized like;
// doSomething() will be from another class
theCore.doSomething()
There are some ideas I produced like
someOtherClass.doSomething(theCore)
which is injecting the main object as a parameter but still someOtherClass needs to be initialized or even a static method which doesn't make me feel comfortable and right way to that.
Actually I do not care if initializing TheCore would bring me a super object that includes all other classes inside initialized and ready to be accessed after I initialized TheCore. All I want in this structure to have a maintainable separate app and methods avaiable if only the main object which is TheCore is this circumstances is initialized.
What is to right way to achive it? I see that Java does not allow extending multiple classes even it if does, I'm not sure it that is right way...
Thanks.
After spending significant amount of time of thought I ended up that
// doSomething() will be from another class
theCore.doSomething()
is not suitable since many java classes could possibly have identical method names. So...
// doSomething() will be from another class
theCore.someOtherClass.doSomething()
would be a better approach.
To make it easier to understand I'll have to follow a complex path to explain it which is starting from the package classes first.
Think that I have a package named Tools and a class inside SomeFancyTool
main
└─java
└─com
└─<domainName>
├─Tools
| └─SomeFancyTool.java
└─TheCore.java
Now this SomeFancyTool.java must have a default access level which is actually package level access, because I don't want this classes to be accessed directly;
SomeFancyTool.java
package com.<domainName>.Tools
class SomeFancyTool{
public String someStringMethod(){
return "Some string!";
}
public int someIntMethod(){
return 123;
}
public boolean someBooleanMethod(){
return true;
}
}
So now we have the SomeFancyTool.java class but TheCore.java cannot access it since it is accesible through its Tools package only. At this point I think of an Initializer class that is gonna be in the same package, initialize these private classes and return them with a function when called. So initiliazer class would look like this;
ToolsInitializer.java
package com.<domainName>.Tools
public class ToolsInitializer{
private SomeFancyTool someFancyTool = new SomeFancyTool();
public SomeFancyTool getSomeFancyTool(){
return someFancyTool;
}
}
Since ToolsInitializer.java can initialize all functional private classes inside in Tools package and also can return them as objects to outside of the package scope, still we are not able to use these methods as we cannot import com.<domainName>.SomeFancyTool from TheCore.java because it is package wide accessible. I think here we can benefit from implementation of the java interface. A class that is not functional alone, so no problem even if it is accessed since it's methods will be nothing but declarations.
At this point I'll rename SomeFancyTool.java to SomeFancyToolImplementation.java which it will be implementing the interface and call SomeFancyTool.java to the interface itself.
SomeFancyTool.java (now as an interface)
package com.<domainName>.Tools
public interface SomeFancyTool{
public String someStringMethod();
public int someIntMethod();
public boolean someBooleanMethod();
}
and lets rename prior SomeFancyTool.java and implement the interface
SomeFancyToolImplementation.java (renamed)
package com.<domainName>.Tools
class SomeFancyToolImplementation implements SomeFancyTool{
#override
public String someStringMethod(){
return "Some string!";
}
#override
public int someIntMethod(){
return 123;
}
#override
public boolean someBooleanMethod(){
return true;
}
}
Now our structure has become like this with the final edits;
main
└─java
└─com
└─<domainName>
├─Tools
| ├─SomeFancyTool.java
| ├─SomeFancyToolImplementation.java
| └─ToolsInitializer.java
└─TheCore.java
Finally we can use our TheCore.java class to call all initializer classes with their methods to receive all these private classes inside as an object. This will allow external apps to call and initialize TheCore first to be able to access other methods.
TheCore.java
public class TheCore{
private SomeFancyToolImplementation someFancyTool;
public static class Builder{
private SomeFancyToolImplementation someFancyTool;
public Builder(){
ToolsInitializer toolsInitializer = new ToolsInitializer();
someFancyTool = toolsInitializer.getSomeFancyTool();
}
public Builder setSomeValues(){
//some values that is needed.
return this;
}
public Builder setSomeMoreValues(){
//some values that is needed.
return this;
}
public TheCore build(){
TheCore theCore = new TheCore();
theCore.someFancyTool = someFancyTool;
return theCore;
}
}
}
All Done and it is ready to use. Now the functional package classes and its methods that it relying on if TheCore is initialized or not, cannot be accessed with out TheCore. And simple usage of this Library from a 3rd Party app would simply be;
3rd Party App
TheCore theCore = new TheCore.Builder()
.setSomeValues("Some Values")
.setMoreSomeValues("Some More Values")
.build();
theCore.someFancyTool.someStringMethod();
Note: Note that a the ToolsInitializer.java is still accessible and could be used the get private method without first calling TheCore but we can always set a checker inside getSomeFancyTool() method to throw error if some prerequisites are not satisfied.
I do not still know if this is a functional structural pattern to use or its just some hard thoughts of mine. And don't know if some pattern is already exist that I just could not see yet but this is the solution I end up with.

Java Generics - way around instantiating wildcard type

I am trying to build a lib that supports deployment of custom implementations of a specific object.
Class A is the deployment entry point that the users will tell how they want things to be configured
Class B will be the object that holds the custom implementation instance
Class C will be the abstract class that the users can extend to create their own custom implementation
Class D will be the custom implementation that extends Class C (NOT PART OF THE LIB)
When the user is setting things up with Class A, I want them to be able to do something like this:
/* this code will not be part of the lib */
ClassA a = new ClassA()
a.setClassCImpl(ClassD.class)
Now when Class B gets instantiated it needs to know to use the custom implementation Class D
/* this code will be part of the lib */
Class<? extends ClassC> classCImpl;
ClassB() {
classCImpl = new ??? // this needs to be an instance of Class D
}
There will be many instances of Class B. I'd rather not need Class B to hold onto an instance of Class A, but I'm not sure this will be possible without using static stuff in Class A.
This sort of pattern is a good use case for using annotations. Some frameworks implement this kind of behavior but you can quite easily achieve it.
If you can allow users to extend B annotations are really convenient.
For example declare your annotation like that :
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.TYPE)
public #interface MeaningfulName {
public Class<? extends ClassC> value(); // you can define a default
}
Now when your users extend B they can add this annotation
#MeaningfulName(ClassD.class)
public class CustomB extends ClassB {
// whatever your class does
}
Then you can extract this at runtime using getAnnotation() and setup some caching maybe to avoid frequent lookups. After obtaining the Class attribute you can get the appropriate instance using your desired strategy (singleton, factory, straight up reflection etc.).
If you just want to stick to a single B class, you can specify various combinations of locations users could use it using #Target and other ElementTypes, although with different ways to extract the annotation.
ClassA:
ClassA {
static Class<? extends ClassC> impl = ClassD.class
}
ClassB:
ClassC classCImpl;
ClassB() {
classCImpl = ClassA.impl.getDeclaredConstructor().newInstance();
}
I think this will work.

Why can't I assign an Scala Object to a Java variable?

I have this monolithic Java-Application that I want to port to newer techniques and I want to apply Scala wherever it makes sense.
Now I translated a rather huge java-singleton class implementation to a Scala object.
In another class I used to do this (JAVA):
public class MyOtherClass
{
protected MyClass myClass;
public MyOtherClass()
{
myClass = MyClass.getInstance();
}
}
Now I'd like to do the following:
public class MyOtherClass
{
protected MySCALAClass myClass;
public MyOtherClass()
{
myClass = MySCALAClass$.MODULE$;
}
}
But this doesn't work. It says:
Required MyScalaClass, Found MyScalaClass$
I also tried to create a small function
def getInstance() = this
but of course this yields the same problem.
Any ideas? I have searched this topic and I see how it is not a problem if you just want to call the methods of the object, but I would need to rewrite many, many calls to the "myClass"-object to even test this.
edit: I'm fully aware that I could rename every call to "myClass" to "MySCALAClass", but that is no real fix, just a workaround and it is tedious for a big project.
I think #neuronaut 's comment is correct.
See following questions:
Scala object MODULE$
Singletons as Synthetic classes in Scala?
The singleton class (MySCALAClass$ in your case) is not a subclass of the original class (MySCALAClass) and so the singleton object (MySCALAClass$.MODULE$) is not an instance of it either.

Is there a better way to provide a helper methods to test a web application than using a single class?

I'm designing UI Tests for a web application with Selenium in JUnit. I have a base test class with something like this from which I inherit my tests:
public class BaseTest {
protected TestSteps test;
protected Assertions assertion;
// set everything up...
}
and the tests then only look like this:
public class TestX extends BaseTest {
#Test
public testFeature1() {
test.clickSomething().enterSomething(); // method chaining
assertion.assertSomething();
//...
}
}
The problem I'm having: There are different modules in the web app, and Assertions/TestSteps methods that only apply to one module clutter the interface of the Assertions/TestSteps class for the other modules.
Thus I tried to split the Assertions/TestSteps up.
The problem is, the method chaining returns instances of TestSteps. Of course, when I have Module1TestSteps with method doSomethingSpecific() then I would expect test.clickSomething().doSomethingSpecific() to work, but it does not, because clickSomething() would return a TestSteps instance, not a Module1TestSteps instance.
I "solved" this by making an AbstractTestSteps<T extends AbstractTestSteps<T> class (which contains all the base TestSteps methods) protected abstract T getThis();.
I then extend this class like this:
public class BaseTestSteps extends AbstractTestSteps<BaseTestSteps> {
// Constructors
protected BaseTestSteps getThis() {
return this;
}
// that's it, the "base methods" are all inherited from AbstractTestSteps...
}
for the base TestSteps and
public class Module1TestSteps extends AbstractTestSteps<Module1TestSteps> {
// same constructors...
protected Module1TestSteps getThis() {
return this;
}
public Module1TestSteps doSomeThingSpecific() {
// do something
return getThis();
}
}
for my specialized TestSteps. It works for now, but I don't like it because of the following reasons:
All the general methods are in the AbstractTestSteps class, but they are used through an instance of BaseTestSteps
What if I have a submodule of Module1? I can't inherit from Module1TestSteps, only from AbstractTestSteps.
I think it's not trivial to understand the relation of these classes when one of my colleagues tries to add a new TestSteps class.
How can this be made better?
Use the Page Object pattern. That is, create an API for each page so that your tests describe navigating and interacting with pages in a way that describes the user's experience.
It has a few benefits that address your concerns:
It uses composition, not inheritance
It is easy to understand and explain to people maintaining the tests because the tests read like a description of somebody using the application

Define Implementation for abstract Object

I am looking for a way to do the following:
A Project :
Defines an abstract class that is called when some events happen (event handler if you will)
Defines the engine that will fire the events using the event handler above
B Project:
Defines the implementation for the abstract class
Runs the engine.
How can i register the implementation class and make sure that is the one being called when the engine runs.
EDIT 1: By register i mean i must somehow define which is the implementation that should be called for that given abstract object
Sorry if the question isn't too clear, let me know if you need some more details
Something like this?
class A implements EventHandlerForB {
...
}
public class B {
private EventHandlerForB eventHandler;
public void registerEventHandler(EventHandlerForB eventHandler) {
this.eventHandler = eventHandler;
}
...
}
public interface EventHandlerForB {
...
}
At runtime, you can have the name of the implementation passed in your A project (with a properties file or a Java system property).
Then you find this class in the classpath with class.forName() and instantiate it with newInstance().
But you'd prefer using a framework like Guice or Spring, that will allow you to glue stuff together in a clean way.
there are several "patterns" that try to address this issue. Using only JDK (6 or above) classes you may want to take a look at java.util.ServiceLoader

Categories

Resources