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.
Related
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.
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 application which consist of a set of services. These services require I/O which is handled through an IOAdapter interface as below:
interface IOAdapter {
void info(Object arg);
void error(Throwable cause);
String read(String prompt);
boolean confirm(String prompt);
}
In the service methods, the input is obtained using some implementation of the adapter which is composed into the service instance. This adapter then handles all I/O (user interactions), and hence allows separation of that concern from the actual business logic.
For example, a typical method method would do something like:
class MyService {
IOAdapter adapter;
MyService () {
adapter = new MyAdapter(); // some implementation
}
void doSomething() {
try {
...
String val = adapter.read("Enter a value: ");
if(adapter.confirm("Are you sure?")) {
adapter.info("Value entered is: " + val);
...
} else {
doSomething();
}
} catch (Exception e) {
adapter.error(e);
...
}
}
}
Now I was able to implement an adapter which does I/O through the Java console. But, can anybody suggest a possible approach if I were to provide an implementation for a Web based adapter where the I/O happens through the browser?
Is there an alternative approach which would help solve this problem in a more straight-forward manner?
If I understand it right, you want to wrap the functionality of an HTTP server in your own service, implementing the IOAdapter interface. I think that this is not "beautiful" in the way the interface IOAdapter is written and used in the MyService class. This is because even if you write a MyHTTPAdapter the adapter.read method cannot be implemented using HTTP.
In HTTP we have two entities communicating. The client sends and the server responds. This cannot be modelled using this interface you propose, since you model only one entity and have only one method for exchanging data, method read. You have to alter the interface design, focusing on a client-server design, then you could wrap an HTTP communication.
EDIT:
Integrating the two paradigms of communication (console communication and HTTP communication) is not a trivial task. I would propose a design imposed by this interface, following the client-server architecture imposed by HTTP, supposing that a console application could implement it too:
//This should be implemented by either the HTTP or the console server Adapter
interface IOAdapter {
IOResponse serveRequest(IORequest request);
}
//This interface should be implemented by both models of IOAdapter
//For example, a subclass of string could also implement this interface in
//order to unify the two models
interface IORequest {
}
//This interface should be implemented by both models of IOAdapter
//For example, a subclass of string could also implement this interface in
//order to unify the two models
interface IOResponse {
}
Hope I helped!
I am creating a instant chat application using RMI. The server sends through certain objects which I need the client to handle.
For example the server will send a JoinedGroupOperation class. In my client application I need to recognise the class and let my handler take over (HandleJoinedGroupOperation). This class will do a bunch of stuff on the client side.
My question is how can I handle classes that come from the server so I don't need to do any if statements? ie
if(server.getResponse() instanceof JoinedGroupOperation){
HandleJoinedGroupOperation handle = new HandleJoinedGroupOperation();
handle.foo();
}
One of the possible option in your case is to use chain of responsibility design patern.
You should create some abstraction of your possible handlers(like HandleJoinedGroupOperation), then link those handlers(preferebly at start time). As a example, create an interface
interface OperationHandler {
void handle(Operation op);
}
where Operation is also a basic type for all possible operations. This type(Operation) can contain a field of enum type OperationType:
enum OperationType {
...
}
Then in the concrete handlers you can simply check this field(although it will contain if statement, but those statements will be encapsulated in each specific handler)
As a simple example, here is a default implementation of a handler
class SimpleHandler implements OperationHandler {
private OperationHandler next;
public void handle(Operation op) {
if (op.getType() == OperationType.SOMEYOURTYPE) {
//do some stuff
} else {
next.handle(op);
}
}
}
In this case your server.getResponse() method simply will return basic type of Operation hierarchy
Also read the article to get more information
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.