Service interface:
public interface UserInterface {
void present();
void onStart();
void onStop();
}
I have two implementations: TextUserInterface and GraphicalUserInterface.
How can I identify the one I want to use when I launch my program? Source
private static void main(String[] args) {
ServiceLoader<UserInterface> uiLoader = ServiceLoader.load(UserInterface.class);
UserInterface ui = uiLoader.? //what to do to identify the one I want to use?
}
I was thinking of introducing an enum with the type of UI, so I could just iterate through all services and pick the one I'd like to, but isn't this approach just a misuse of services? In this case when I want to pick GraphicalUserInterface I could just skip the ServiceLoader part and just instantiate one. The only difference I see is fact that without services, I'd have to require the GraphicalUserInterface module, which "kind of" breaks the encapsulation.
I don't actually think that it would be a misuse of it. As a matter of fact, what you get from ServiceLoader.load(...) method is an Iteratable object, and if you need for a specific service, you will have to iterate through all the available instances.
The idea of the enum is not that bad, but I suggest that you take advantage of the Java stream and filter for the instance you need. For example, you might have something like that:
enum UserInterfaceType {
TEXT_UI, GRAPH_UI;
}
public interface UserInterface {
UserInterfaceType getTypeUI();
...
}
// In your main method
ServiceLoader<UserInterface> uiLoader = ServiceLoader.load(UserInterface.class);
UserInterface ui = uiLoader.steam()
.filter(p -> p->getTypeUI() == <TypeUIyouNeed> )
.findFirst()
.get();
That is open to a number of possibilities, for example you can put this is a separated method, which receives in input a UserInterfaceType value, and it can retrieve the service implementation based on the type enum value you passed.
As I said, that is just the main idea, but definitely you are not doing any misuse of the ServiceLoader.
Related
I wish to have the bridge pattern applied for a project, basically I want this project to be able to trigger requests towards multiple different channels.
Example, I want to create messages which can be SMSs, E-mails or Viber for example... Obviously each of them is a message, but each with some different things, and so I wanted to have the Bridge applied there.
Is the bridge pattern the right one? If yes, how can it be implemented? In case another one should be used, also, please let me know how to use it in this context.
Thank you!
DISCLAMER This example is built from my understanding of the bridge pattern. If you feel like I'm not giving an appropriate definition, please let me know and I will happily remove it.
Bridge pattern is a good guess, but not for your objects. You can simply use polymorphism to create an Abstract Message class. This class could be extend in all of your specific objects.
public abstract class Message {
/* ... */
}
public class SmsMessage extends Message {
/* ... */
}
Where the bridge pattern could be useful is when you want to actually send the message. Chances are you are going to need different protocol to send different message so implementing a bridge pattern is a good idea.
The benefit of the bridge pattern is to generalize some classes, that way, if you need to add a new type of those classes, the code that uses it doesn't change.
Lets say your sending logic is tangle into a 3000 line class and that each time you want to send a message, you need to check what type of message it is, to send via the correct protocol. Well, adding a new message type, like FlyingPigeonMessage would be a real pain, since you need to replace every code that check what message to send.
On the other hand, if your 3000 line classes never know what TYPE of message they are, only that they are MESSAGEs, they adding a new type is a walk in the park. With that in mind, here is a simple implementation of the bridge pattern.
First, we need to define our bridge. In our case, it can be an interface that implements a simple method send.
public interface IMessageProvider {
public void send(Message message)
}
We then need to create different implementation of that Interface, one for each type of message. Here I'm only going to build the SMS class because this is an example.
public class SmsMessageProvider implements IMessageProvider {
#override
public void send(Message message) {
/* call a sms service or somehting... */
}
}
Once we have multiple providers, we need a way to instanciate them depending on a given condition. I like to use factories for that, you can pass it an object and depending on it's type, you get a specific implementation.
/**
* Creates message providers.
*/
public class MessageProviderFactory {
public static IMessageProvider getProviderForMessage(Message message) {
// we return an implementation of IMessageProbvider depending on the type of message.
if(message instanceOf SmsMessage) {
return new SmsMessageProvider();
} else {
// other types of message
}
}
}
Now, we have a bridge interface, we have implementations and we have a factory. All we need is to send the message. The beauty of the bridge pattern is that the function that call the send methods doesn't need to know exactly what object it has. Which make it way easier to maintain.
public class Application() {
public static void main(String[] args) {
Message message;
Boolean isSendingSMS = true; // user prefer sms over email
// we build the message depending on the config.
if(isSendingSMS) {
message = new SmsMessage("my awesome message");
} else {
/* ... */
}
// will send the message we built.
Application.sendMessage(message);
}
public static void sendMessage(Message message) {
// for a given message, we retreive the appropriate provider
IMessageProvider provider = MessageProviderFactory.getProviderForMessage(message);
// using this provider we send the message
provider.send(message);
}
}
In the end, we end up sending a message via the correct provider without having to actually know what provider it was. We used the bridge pattern to build the provider and simple polymorphism to build our object.
NOTE I havn't done Java in a long time, this code might not be syntaxically valid but I hope it provide a good example.
The program I am working on has a distributed architecture, more precisely the Broker-Agent Pattern. The broker will send messages to its corresponding agent in order to tell the agent to execute a task. Each message sent contains the target task information(the task name, configuration properties needed for the task to perform etc.). In my code, each task in the agent side is implemente in a seperate class. Like :
public class Task1 {}
public class Task2 {}
public class Task3 {}
...
Messages are in JSON format like:
{
"taskName": "Task1", // put the class name here
"config": {
}
}
So what I need is to associate the message sent from the broker with the right task in the agent side.
I know one way is to put the target task class name in the message so that the agent is able to create an instance of that task class by the task name extracted from the message using reflections, like:
Class.forName(className).getConstructor(String.class).newInstance(arg);
I want to know what is the best practice to implement this association. The number of tasks is growing and I think to write string is easy to make mistakes and not easy to maintain.
If you're that specific about classnames you could even think about serializing task objects and sending them directly. That's probably simpler than your reflection approach (though even tighter coupled).
But usually you don't want that kind of coupling between Broker and Agent. A broker needs to know which task types there are and how to describe the task in a way that everybody understands (like in JSON). It doesn't / shouldn't know how the Agent implements the task. Or even in which language the Agent is written. (That doesn't mean that it's a bad idea to define task names in a place that is common to both code bases)
So you're left with finding a good way to construct objects (or call methods) inside your agent based on some string. And the common solution for that is some form of factory pattern like: http://alvinalexander.com/java/java-factory-pattern-example - also helpful: a Map<String, Factory> like
interface Task {
void doSomething();
}
interface Factory {
Task makeTask(String taskDescription);
}
Map<String, Factory> taskMap = new HashMap<>();
void init() {
taskMap.put("sayHello", new Factory() {
#Override
public Task makeTask(String taskDescription) {
return new Task() {
#Override
public void doSomething() {
System.out.println("Hello" + taskDescription);
}
};
}
});
}
void onTask(String taskName, String taskDescription) {
Factory factory = taskMap.get(taskName);
if (factory == null) {
System.out.println("Unknown task: " + taskName);
}
Task task = factory.makeTask(taskDescription);
// execute task somewhere
new Thread(task::doSomething).start();
}
http://ideone.com/We5FZk
And if you want it fancy consider annotation based reflection magic. Depends on how many task classes there are. The more the more effort to put into an automagic solution that hides the complexity from you.
For example above Map could be filled automatically by adding some class path scanning for classes of the right type with some annotation that holds the string(s). Or you could let some DI framework inject all the things that need to go into the map. DI in larger projects usually solves those kinds of issues really well: https://softwareengineering.stackexchange.com/questions/188030/how-to-use-dependency-injection-in-conjunction-with-the-factory-pattern
And besides writing your own distribution system you can probably use existing ones. (And reuse rather then reinvent is a best practice). Maybe http://www.typesafe.com/activator/template/akka-distributed-workers or more general http://twitter.github.io/finagle/ work in your context. But there are way too many other open source distributed things that cover different aspects to name all the interesting ones.
I have a Java bot running based on the PircBotX framework. An IRC bot simply replies on commands. So now I have a list of static strings e.g.; !weather, !lastseen and the likes in my Main.java file.
For each command I add I create a new static string and I compare each incoming message if it starts with any of the defined commands.
Pseudocode
Receive message `m`
if m matches !x
-> do handleX()
if m matches !y
-> do handleY()
This is basicly a very large if test.
What I would like to do is create some sort of skeleton class that perhaps implements an interface and defines on which command it should act and a body that defines the code it should execute. Something I'm thinking of is shown below:
public class XkcdHandler implements CommandHandlerInterface
{
public String getCommand()
{
return "!xkcd";
}
public void HandleCommand(String[] args, Channel ircChannel)
{
// Get XKCD..
ircChannel.send("The XKCD for today is ..");
}
}
With such a class I could simply add a new class and be done with it. Now I have to add the command, add the if test in the list, and add the method to the Main.java class. It is just not a nice example of software architecture.
Is there a way that I could create something that automatically loads these classes (or instances of those classes), and then just call something like invokeMatchingCommand()? This code could then iterate a list of loaded commands and invoke HandleCommand on the matching instance.
Update
With the answer of BalckEye in mind I figured I could load all classes that are found in a package (i.e., Modules), instantiate them and store them in a list. This way I could handle each message as shown in his answer (i.e., iterate the list and execute the class method for each matching command).
However, it seems, according to this thread, that it's not really viable to do. At this point I'm having a look at classloaders, perhaps that would be a viable solution.
There are several ways I think. You can just use a Map with the command as the key and an interface which executes your code as the value. Something like this:
Map<String, CommandInterface> commands = new ....
and then use the map like this:
CommandInterface cmd = commands.get(command);
if(cmd != null) {
cmd.execute();
}
You are looking for the static block, for instance:
class main {
private static List<CommandHandlerInterface> modules = new ArrayList<...>();
static { // gets called when a static member gets accessed for the first time (once per class)
modules.add(new WeatherCommand());
// etc.
}
// method here which iterates over modules and checks
}
I'm fairly new to Java. I'm coming from PHP and I used to create registry classes in php using the magic __get and __set methods. So that other parts of the system can easily do:
registry.foo = new Foo();
I should mention I'm trying to create game engine. Here is my registry in Java atm:
class Registry {
private static Map<String, Object> box = new HashMap<String, Object>();
public static Object get(String key) {
if (Registry.box.get(key) != null) {
return Registry.box.get(key);
}else {
return null;
}
}
public static void set(String key, Object o) {
Registry.box.put(key, o);
}
}
Then for the other parts of the system to access the registry, I currently need this whole thing:
((Object) Registry.get("Object")).doSomething();
Which is really a lot of code. In php this would be accomplished by simply:
Registry.foo.doSomething();
Any way to make this a bit more simpler? I guess I could make public fields, but then the regsitry class would need to implicitly create these fields as the possibility of new objects may need to be added which are unknown to the registry class itself, which is.. annoying :P
Thanks in advance!
This is a two pronged problem:
Java is a statically type language, and does not offer in-language flexibility for defining objects at runtime (you can use a library to synthesize classes at runtime, but, see #2)
A global registry for objects defeats a lot of safeties in a type-safe language. If your entire application centers around getting and putting objects into a global Map, there likely safer and less-coupled designs.
How can this be solved?
Redesign your application structure to not need a global map.
Use a dynamic language subset for Java (such as Groovy).
Use Scala 2.10 (JVM compatible) which features a Dynamic type which does exactly what you want.
First of all this method is too verbose:
public static Object get(String key) {
if (Registry.box.get(key) != null) {
return Registry.box.get(key);
}else {
return null;
}
}
It could be just:
public static Object get(String key) {
return Registry.box.get(key);
}
But second, this is definitely a bad design. Global repository - doesn't sound reasonable. A storage of objects of all types by string key - it's terrible.
Any way to make this a bit more simpler?
Not in any practical way. Java is a statically typed language, and the structure of objects has to be known up front. The very idea of an equivalent of PHP's __get and __set is antithetical to the language.
For what it's worth, your "registry" looks like bad design anyway. (Admittedly making some pretty wild assumptions from the little code you've shown.) You shouldn't need a global repository of what appear to be unrelated objects. You should consider some sort of dependency injection instead.
Based on your comment, instead of structuring your code like this:
class World implements GameSystem {
public void update() {
Registry.get("game").doSomething();
}
}
you should do:
class World implements GameSystem {
Game game;
public World(Game game) { // and other dependencies
this.game = game;
}
public void update() {
this.game.doSomething();
}
}
The idea is that components of your program don't really have any business knowing how to find the other components. It also makes dependencies between the components explicit, and helps you avoid circular dependencies.
I am trying to understand the most suitable (Java) design pattern to use to process a series of messages. Each message includes a "type" which determines how the data contained in the message should be processed.
I have been considering the Command pattern, but are struggling to understand the roles/relevance of the specific Command classes. So far, I have determined that the receiver will contain the code that implements the message processing methods. Concrete commands would be instantiated based on message type. However, I have no idea how the actual message data should be passed. Should it be passed to the receiver constructor with the appropriate receiver methods being called by the concrete command execute method? Maybe the message data should be passed in the receiver action method invocations?
I am fairly new to all of this so any guidance would be appreciated.
This may help:
public interface Command {
public void execute(String msg);
}
public class AO1Command implements Command {
Receiver rec = new Receiver();
public void execute(String msg) {
rec.admit(msg);
}
}
public class CommandFactory {
public protected CommandFactory () { }
public static Command getInstance(String type) {
if (type.equals("A01")) return new A01Command();
else if (type.equals("A02")) return new A02Command();
else {
return null;
}
}
Ok, your title says a pattern for handling events. If you are talking about an actual event framework, then the Observer/Observable pattern comes to mind. This would work when you want do fire an event of some type, then have event handlers pick up the processing of the events.
Seems like your problem is in the implementation details of the command pattern. Can you post some code that shows where you are stuck?
Note that patterns are not mutually exclusive, you could use the command pattern in the context of the Observable pattern.
EDIT -- based on your code, you should
1) make the CommandFactory static.
2) pass the type to the getCommand method, which should also be static.
3) You don't need reflection for this, you can simply do
if (type == "type1") return new Command1();
else if (type == "type2") return new Command2();
...
Im not saying you can't use reflection, I'm saying its overcomplicating what you are trying to do. Plus, they way you are doing it binds the the String that represents the message type to the implementation details of the command class names, which seems unnecessary.
You are on the right track. A Command pattern is the appropriate solution to the outlined problem.
To answer your question, you would have your CommandFactory instantiate an appropriate Command instance based on the data differentiator (in this case some data in your message). You would then invoke a method on the Command instance, passing in your message. It is common (best) practice to call this method Execute(...), but you can call it whatever you want.
You may want to take a look to the Jakarta Digester project (to process XML), it has a SAX implementation, wich is an event based API as explained here http://www.saxproject.org/event.html, it's a short explanation but could serve as a starting point for you.