I'm trying to find a framework, or a nice way of implementing a way combining various components, similar to an electronics kit. This is so that it can be wired together using xml (e.g. Spring). I want the users to be able to string together different components without having to worry about Java.
The set up I'm thinking of would have something like the following:
public interface Input<T> {
public T getValue();
}
public interface Output<T> {
public void setValue(T value);
}
public class Wire<T> implements Input<T>, Output<T> {
private T value;
public T getValue() { return value; }
public void setValue(T value) { this.value = value ; };
}
And then components would be something like
public interface Component {
public void evaluate();
}
public class Multiplier implements Component {
private Input<Double> inA;
private Input<Double> inB;
private Output<Double> out;
public Multiplier(Input<Double> inA, Input<Double> inB, Output<Double> out) {
this.inA = inA;
this.inB = inB;
this.out = out;
}
public void evaluate() {
out.setValue(inA.getValue() * inB.getValue());
}
}
main() {
Wire inA = new Wire();
Wire squareOut = new Wire();
Component squarer = new Multiplier(inA, inA, output)
}
So you could tie outputs of one component into the input of another. I've toyed with the idea of the Wires knowing about what outputs they're connected to, so that they can call evaluate on their components... but I think it might be easier to keep a separate "clock" so that circular dependencies can be controlled.
It's not hard to implement, I'd just rather use a public library if there is one already out there. I've struggled to find one.
Any advice about implementing something similar, or what to do instead would be really helpful.
You are talking about Dependency Injection Framework.
Look at Spring, Google Guice or PicoContainer.
Related
I have this old code implemented in hateoas:1.0
public class StaticPathLinkBuilder extends LinkBuilderSupport<StaticPathLinkBuilder> {
#Override
protected StaticPathLinkBuilder createNewInstance(UriComponentsBuilder builder) {
return new StaticPathLinkBuilder(builder);
}
I updated my code to hateoas 2.6.7 but the code is changed this way:
public class StaticPathLinkBuilder extends LinkBuilderSupport<StaticPathLinkBuilder> {
#Override
protected StaticPathLinkBuilder createNewInstance(UriComponents components, List<Affordance> affordances) {
return null;
}
What is the proper way to implement this change? I tried this:
#Override
protected StaticPathLinkBuilder createNewInstance(UriComponents components, List<Affordance> affordances) {
return new StaticPathLinkBuilder(UriComponentsBuilder.newInstance().uriComponents(components));
}
But it's not clear how I have to implement the code that I can send affordances.
Can you advice what is the proper way to implement this?
As you can see in its source code LinkBuilderSupport already provides a constructor with the two required arguments, UriComponents and List<Affordance>.
In the own library codebase, different LinkBuilders implementations as BasicLinkBuilder or TemplateVariableAwareLinkBuilderSupport already takes advantage of this fact in their implementations.
In your use case, you could try something similar to this:
public class StaticPathLinkBuilder extends LinkBuilderSupport<StaticPathLinkBuilder> {
private StaticPathLinkBuilder(UriComponents components, List<Affordance> affordances) {
super(components, affordances);
}
#Override
protected StaticPathLinkBuilder createNewInstance(UriComponents components, List<Affordance> affordances) {
return new StaticPathLinkBuilder(components, affordances);
}
}
I don't have a GUI (my classes are part of a Minecraft Mod). I wanted to be able to mimic C# event framework: A class declares events and lets others subscribe to them.
My first approach was to create a class called EventArgs and then do something like this:
public class EventArgs
{
public boolean handled;
}
#FunctionalInterface
public interface IEventHandler<TEvtArgs extends EventArgs>
{
public void handle(Object source, TEvtArgs args);
}
public class Event<TEvtArgs extends EventArgs>
{
private final Object owner;
private final LinkedList<IEventHandler<TEvtArgs>> handlers = new LinkedList<>();
public Event(Object owner)
{
this.owner = owner;
}
public void subscribe(IEventHandler<TEvtArgs> handler)
{
handlers.add(handler);
}
public void unsubscribe(IEventHandler<TEvtArgs> handler)
{
while(handlers.remove(handler));
}
public void raise(TEvtArgs args)
{
for(IEventHandler<TEvtArgs> handler : handlers)
{
handler.handle(owner, args);
if(args.handled)
break;
}
}
}
Then a class would do something like this:
public class PropertyChangedEvtArgs extends EventArgs
{
public final Object oldValue;
public final Object newValue;
public PropertyChangedEvtArgs(final Object oldValue, final Object newValue)
{
this.oldValue = oldValue;
this.newValue = newValue;
}
}
public class SomeEventPublisher
{
private int property = 0;
private final Random rnd = new Random();
public final Event<PropertyChangedEvtArgs> PropertyChanged = new Event<>(this);
public void raiseEventOrNot(int value)
{
if(rnd.nextBoolean())//just to represent the fact that the event is not always raised
{
int old = property;
property = value;
PropertyChanged.raise(new PropertyChangedEvtArgs("old(" + old + ")", "new(" + value + ")"));
}
}
}
public class SomeSubscriber
{
private final SomeEventPublisher eventPublisher = new SomeEventPublisher();
public SomeSubscriber()
{
eventPublisher.PropertyChanged.subscribe(this::handlePropertyAChanges);
}
private void handlePropertyAChanges(Object source, PropertyChangedEvtArgs args)
{
System.out.println("old:" + args.oldValue);
System.out.println("new:" + args.newValue + "\n");
}
public void someMethod(int i)
{
eventPublisher.raiseEventOrNot(i);
}
}
public class Main
{
private static final SomeSubscriber subscriber = new SomeSubscriber();
public static void main(String[] args)
{
for(int i = 0; i < 10; ++i)
{
subscriber.someMethod(i);
}
}
}
The biggest problem with this naïve approach is that it breaks proper encapsullation by exposing raise as public. I can't see a way around it, and maybe my whole pattern is wrong. I would like some ideas.
There's also a related problem: I would like the events to be raised immediately after the method raising them returns. Is there a way to synchronize this using threads or some other construct? The caller code, of course, can't be involved in the task of synchronization. It has to be completely transparent to it.
The best thing to do here is to avoid implementing your own event framework in the first place, and instead rely on some existing library. Out of the box Java provides EventListener, and at a minimum you can follow the patterns documented there. Even for non-GUI applications most of this advice applies.
Going beyond the JDK Guava provides several possible options, depending on your exact use case.
The most likely candidate is EventBus, which:
allows publish-subscribe-style communication between components without requiring the components to explicitly register with one another (and thus be aware of each other).
Or ListenableFuture (and ListeningExecutorService) which:
allows you to register callbacks to be executed once [a task submitted to an Executor] is complete, or if the computation is already complete, immediately. This simple addition makes it possible to efficiently support many operations that the basic Future interface cannot support.
Or the Service API which:
represents an object with an operational state, with methods to start and stop. For example, webservers, RPC servers, and timers can implement the Service interface. Managing the state of services like these, which require proper startup and shutdown management, can be nontrivial, especially if multiple threads or scheduling is involved.
This API similarly lets you register listeners to respond to state changes in your services.
Even if none of these options directly work for your use case, take a look at Guava's source code for examples of event-driven behavior and listeners you can try to emulate.
I'm writing simple Chat System. There are should be two implementations of communication:
using Serialization
and XML (own protocol).
Implementation is chosen by user in GUI.
So, is it okay to use if-else or switch for choosing implementation ?
I have thought about Java Reflection but I can't figure out how to realize it.
Any suggestions ?
I'd say it can be "okay" to use a if-else or switch statement to choose the implementation. A better (and more OOP) approach would be something along these lines:
//////////////////////////////////
// The communication interfaces
//////////////////////////////////
public interface IChatCommunicationFactory {
public String toString();
public IChatCommunication create();
}
public interface IChatCommunication {
public sendChatLine(String chatLine);
public registerChatLineReceiver(IChatLineReceiver chatLineReceiver);
}
public interface IChatLineReceiver {
public void onChatLineReceived(String chatLine);
}
//////////////////////////////////
// The communication interface implementations
//////////////////////////////////
public class XMLChatCommunicationFactory implements IChatCommunicationFactory {
public String toString() {
return "XML implementation";
}
public IChatCommunication create() {
return new XMLChatCommunication();
}
}
public class XMLChatCommunication implements IChatCommunication {
private XMLProtocolSocket socket;
public XMLChatCommunication() {
// set up socket
}
public sendChatLine(String chatLine) {
// send your chat line
}
public registerChatLineReceiver(IChatLineReceiver chatLineReceiver) {
// start thread in which received chat lines are handled and then passed to the onChatLineReceived of the IChatLineReceiver
}
}
// Do the same as above for the Serialization implementation.
//////////////////////////////////
// The user interface
//////////////////////////////////
public void fillListBoxWithCommuncationImplementations(ListBox listBox) {
listBox.addItem(new XMLChatCommunicationFactory());
listBox.addItem(new SerializationChatCommunicationFactory());
}
public IChatCommunication getChatCommunicationImplementationByUserSelection(ListBox listBox) {
if (listBox.selectedItem == null)
return null;
IChatCommunicationFactory factory = (IChatCommunicationFactory)listBox.selectedItem;
return factory.create();
}
You could go one step further and implement something like a ChatCommunicationFactoryRegistry where each IChatCommunicationFactory is registerd. That would help to move the "business" logic out of the user interface because the fillListBoxWithCommuncationImplementations() method would only need to know the registry, not the individual implementations anymore.
Inheritance and plain old Java is the 'pattern' to use here. Instantiate the implementation to be used, and save a reference to it in the object that needs to use it. When the user switches methods, instantiate the new one.
We are working on a multi process projects which use RMI for RPCs.
The problem that we are facing is that the main object which must be passed between processes is very big (when serialized), and this dropped the performance of the code dramatically.
Since, none of the processes change the whole object and only alter small parts of it, we decided to just pass "the modifications" through RMI.
but I found no proper way to implement such concept. The first idea was to keep track of all changes of the main instance. But this seems not easy according to this.
I need a way which we can:
develop fast
performs fast
any suggestion?
Just make this 'main object' a remote object that implements a remote interface, and export it, instead of serializing it backwards and forwards.
I think the best way is to customize your serialization so you will be able to send only the changes. you can do it by implementing private method of
private void writeObject(java.io.ObjectOutputStream stream) and of course also readObject from the other side. well, what you should do in this functions?
I suggest you will manage a bitmap of all the members that were changed and only send them in the serialization, just change the unchanged members to null send the object in serialization and than return there values. in the other side read the bitmap and than you will know how to
First time you need to pass the whole object.
Use PropertyChangeListener on the object, this would generate an PropertyChangeEvent.
You can pass the PropertyChangeEvent around. It has the getSource(), by which you can identify the object. If this is not enough, if you need IOR or any other sort of reference, create a wrapper and sent it across..
-Maddy
Have a look to http://docs.oracle.com/javase/tutorial/uiswing/events/propertychangelistener.html
public class Test {
PropertyChangeSupport pcs = new PropertyChangeSupport(this);
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
String oldName = this.name;
this.name = name;
pcs.firePropertyChange("name", oldName, name);
}
public int getAge() {
return age;
}
public void setAge(int age) {
int oldAge = this.age;
this.age = age;
pcs.firePropertyChange("age", oldAge, age);
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
pcs.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
pcs.removePropertyChangeListener(listener);
}
public Test(){
}
public static void main (String[] args){
Test myTestObject = new Test();
myTestObject.addPropertyChangeListener(new MyPropertyChangeListener());
myTestObject.setAge(12);
myTestObject.setName("Rick");
myTestObject.setName("Andrew");
}
private static class MyPropertyChangeListener implements PropertyChangeListener {
#Override
public void propertyChange(PropertyChangeEvent event) {
String clazz = event.getSource().getClass().getName();
System.out.println(clazz+"::"+event.getPropertyName()+" changed from "+event.getOldValue()+" to "+event.getNewValue());
}
}
}
This is a simple example but using this approach you can create different PropertyChangeListeners and provide different logic inside theirs method propertyChange.
Also is possible to fire only the changes over a small set of attributes and not over all of them (not storing the oldValue and not firing the firePropertyChange method of PropertyChangeSupport).
Of course that you can use AOP, but perhaps you are looking for a solution like presented above. I hope this helps.
I am going to develop a web crawler using java to capture hotel room prices from hotel websites.
In this case I want to capture room price with the room type and the meal type, so my algorithm should be intelligent to handle that.
For example:
Room type: Deluxe
Meal type: HalfBoad
price : $20.00
The main problem is room prices can be in different ways in different hotel sites. So my algorithm should be independent from hotel sites.
I am plan to use above room types and meal types as a fuzzy sets and compare the words in webpage with above fuzzy sets using a suitable membership function.
Anyone experienced with this? or have an idea for my problem?
There are two ways to approach this problem:
You can customize your crawler to understand the formats used by different Websites; or
You can come up with a general ("fuzzy") solution.
(1) will, by far, be the easiest. Ideally you want to create some tools that make this easier so you can create a filter for any new site in minimal time. IMHO your time will be best spent with this approach.
(2) has lots of problems. Firstly it will be unreliable. You will come across formats you don't understand or (worse) get wrong. Second, it will require a substantial amount of development to get something working. This is the sort of thing you use when you're dealing with thousands or millions of sites.
With hundreds of sites you will get better and more predictable results with (1).
As with all problems, design can let you deliver value adapt to situations you haven't considered much more quickly than the general solution.
Start by writing something that parses the data from one provider - the one with the simplest format to handle. Find a way to adapt that handler into your crawler. Be sure to encapsulate construction - you should always do this anyway...
public class RoomTypeExtractor
{
private RoomTypeExtractor() { }
public static RoomTypeExtractor GetInstance()
{
return new RoomTypeExtractor();
}
public string GetRoomType(string content)
{
// BEHAVIOR #1
}
}
The GetInstance() ,ethod lets you promote to a Strategy pattern for practically free.
Then add your second provider type. Say, for instance, that you have a slightly more complex data format which is a little more prevalent than the first format. Start by refactoring what was your concrete room type extractor class into an abstraction with a single variation behind it and have the GetInstance() method return an instance of the concrete type:
public abstract class RoomTypeExtractor
{
public static RoomTypeExtractor GetInstance()
{
return SimpleRoomTypeExtractor.GetInstance();
}
public abstract string GetRoomType(string content);
}
public final class SimpleRoomTypeExtractor extends RoomTypeExtractor
{
private SimpleRoomTypeExtractor() { }
public static SimpleRoomTypeExtractor GetInstance()
{
return new SimpleRoomTypeExtractor();
}
public string GetRoomType(string content)
{
// BEHAVIOR #1
}
}
Create another variation that implements the Null Object pattern...
public class NullRoomTypeExtractor extends RoomTypeExtractor
{
private NullRoomTypeExtractor() { }
public static NullRoomTypeExtractor GetInstance()
{
return new NullRoomTypeExtractor();
}
public string GetRoomType(string content)
{
// whatever "no content" behavior you want... I chose returning null
return null;
}
}
Add a base class that will make it easier to work with the Chain of Responsibility pattern that is in this problem:
public abstract class ChainLinkRoomTypeExtractor extends RoomTypeExtractor
{
private final RoomTypeExtractor next_;
protected ChainLinkRoomTypeExtractor(RoomTypeExtractor next)
{
next_ = next;
}
public final string GetRoomType(string content)
{
if (CanHandleContent(content))
{
return GetRoomTypeFromUnderstoodFormat(content);
}
else
{
return next_.GetRoomType(content);
}
}
protected abstract bool CanHandleContent(string content);
protected abstract string GetRoomTypeFromUnderstoodFormat(string content);
}
Now, refactor the original implementation to have a base class that joins it into a Chain of Responsibility...
public final class SimpleRoomTypeExtractor extends ChainLinkRoomTypeExtractor
{
private SimpleRoomTypeExtractor(RoomTypeExtractor next)
{
super(next);
}
public static SimpleRoomTypeExtractor GetInstance(RoomTypeExtractor next)
{
return new SimpleRoomTypeExtractor(next);
}
protected string CanHandleContent(string content)
{
// return whether or not content contains the right format
}
protected string GetRoomTypeFromUnderstoodFormat(string content)
{
// BEHAVIOR #1
}
}
Be sure to update RoomTypeExtractor.GetInstance():
public static RoomTypeExtractor GetInstance()
{
RoomTypeExtractor extractor = NullRoomTypeExtractor.GetInstance();
extractor = SimpleRoomTypeExtractor.GetInstance(extractor);
return extractor;
}
Once that's done, create a new link for the Chain of Responsibility...
public final class MoreComplexRoomTypeExtractor extends ChainLinkRoomTypeExtractor
{
private MoreComplexRoomTypeExtractor(RoomTypeExtractor next)
{
super(next);
}
public static MoreComplexRoomTypeExtractor GetInstance(RoomTypeExtractor next)
{
return new MoreComplexRoomTypeExtractor(next);
}
protected string CanHandleContent(string content)
{
// Check for presence of format #2
}
protected string GetRoomTypeFromUnderstoodFormat(string content)
{
// BEHAVIOR #2
}
}
Finally, add the new link to the chain, if this is a more common format, you might want to give it higher priority by putting it higher in the chain (the real forces that govern the order of the chain will become apparent when you do this):
public static RoomTypeExtractor GetInstance()
{
RoomTypeExtractor extractor = NullRoomTypeExtractor.GetInstance();
extractor = SimpleRoomTypeExtractor.GetInstance(extractor);
extractor = MoreComplexRoomTypeExtractor.GetInstance(extractor);
return extractor;
}
As time passes, you may want to add ways to dynamically add new links to the Chain of Responsibility, as pointed out by Cletus, but the fundamental principle here is Emergent Design. Start with high quality. Keep quality high. Drive with tests. Do those three things and you will be able to use the fuzzy logic engine between your ears to overcome almost any problem...
EDIT
Translated to Java. Hope I did that right; I'm a little rusty.