The Command pattern has an IReceiver interface with few methods and corresponding to each method there are concrete Command objects (implementing an interface ICommand with execute() method).
I have read that the client knows about the concrete receiver and concrete command and it is usually the client setting up the receiver object in the concrete command object. Then why it is said it decouples the sender and the receiver?
When the client already knows the concrete receiver then I feel this is not loose coupling and also the client in this case can directly call the APIs (methods) on the receiver object.
You can think of Command pattern workflow as follows.
Command declares an interface for all commands, providing a simple execute() method which asks the Receiver of the command to carry out an operation.
The Receiver has the knowledge of what to do to carry out the request.
The Invoker holds a command and can get the Command to execute a request by calling the execute method.
The Client creates ConcreteCommands and sets a Receiver for the command.
The ConcreteCommand defines a binding between the action and the receiver.
When the Invoker calls execute the ConcreteCommand will run one or more actions on the Receiver.
Have a look at sample code to understand things in better way.
public class CommandDemoEx{
public static void main(String args[]){
// On command for TV with same invoker
Receiver r = new TV();
Command onCommand = new OnCommand(r);
Invoker invoker = new Invoker(onCommand);
invoker.execute();
// On command for DVDPlayer with same invoker
r = new DVDPlayer();
onCommand = new OnCommand(r);
invoker = new Invoker(onCommand);
invoker.execute();
}
}
interface Command {
public void execute();
}
class Receiver {
public void switchOn(){
System.out.println("Switch on from:"+this.getClass().getSimpleName());
}
}
class OnCommand implements Command{
private Receiver receiver;
public OnCommand(Receiver receiver){
this.receiver = receiver;
}
public void execute(){
receiver.switchOn();
}
}
class Invoker {
public Command command;
public Invoker(Command c){
this.command=c;
}
public void execute(){
this.command.execute();
}
}
class TV extends Receiver{
public TV(){
}
public String toString(){
return this.getClass().getSimpleName();
}
}
class DVDPlayer extends Receiver{
public DVDPlayer(){
}
public String toString(){
return this.getClass().getSimpleName();
}
}
output:
java CommandDemoEx
Switch on from:TV
Switch on from:DVDPlayer
To answer your question :
I have read client knows about the concrete receiver and concrete command and it is usually client setting up the receiver object in the concrete command object. Then why it is said it decouples the sender and the receiver
To standardize the words, replace "sender" with "invoker". Now go through the code.
Invoker simply executes the ConcreteCommand (OnCommand in this case) by passing ConcreteReceiver.
ConcreteCommand executes Command through ConcreteReceiver i.e. ConcreteCommand defines binding between Action and Receiver.
If you see the workflow, Invoker does not change with additional commands and you can add business logic in execute() method of Invoker like java.lang.Thread, which has been explained as below.
In this way Client (sender) and Receiver are loosely couple through Invoker, which has knowledge of what command to be executed.
Thread example from this link
You can create Thread by implementing Runnable object.
Thread t = new Thread (new MyRunnable()).start();
=>
Invoker invoker = new Invoker(new ConcreteCommand());
invoker.start()
and you have logic in start() to call ConcreteCommand.execute() which is run() in above case.
start() method will call run() method in Thread. What happens if you directly call run() method directly? It won't be treated as thread.
Like start() method of this thread, you can add some business logic in Invoker.
public synchronized void start() {
/**
* This method is not invoked for the main method thread or "system"
* group threads created/set up by the VM. Any new functionality added
* to this method in the future may have to also be added to the VM.
*
* A zero status value corresponds to state "NEW".
*/
if (threadStatus != 0)
throw new IllegalThreadStateException();
group.add(this);
start0();
if (stopBeforeStart) {
stop0(throwableFromStop);
}
}
private native void start0(); // Native code is not here but this method will call run() method
public void run() {
if (target != null) {
target.run();
}
}
EDIT:
On your last query
Here we are creating the command object, Receiver object and Invoker Object.Then passing the receiver object in the command object and then passing the command object in invoker object. This we do for each Receiver like we do here for TV and DVDPlayer. Also in the method 'main' Object of TV and DVDPlayer are known and in fact are created. We can simply do tvObject.switchOn() and dvdPlayer.switchOn(). How does Command pattern help
Client need not worry about changes in Receiver class. Invoker directly works on ConcreteCommand, which has Receiver object. Receiver object may change siwtchOn() to switchOnDevice() in future. But client interaction does not change.
If you have two different commands like switchOn() and switchOff(), still you can use same Invoker.
Directly from Wikipedia:
The command pattern is a behavioral design pattern in which an object is used to encapsulate all information needed to perform an action or trigger an event at a later time.
Edit
After re-reading the Gang of Four's section on the Command pattern, I thought up a better scenario. Let's say you have a GUI library, which defines the following:
public interface Command {
public void execute();
}
public class Button {
private Command command;
public Button(Command command) {
this.command = command;
}
public void click() {
command.execute();
}
}
The Button, in this case, is the receiver of a command, and your code, that creates actual instances of Buttons, is the client. Of course, when you create a button, you have to define some concrete implementations of the Command interface. But the GUI library does not need to know about these classes; all it needs is the interface. This is how the GUI code is decoupled from your code.
Loose coupling isn't the main goal of Command
Here's the class diagram for the Command pattern from the original Design Patterns book:
As you said, Client knows about the ConcreteCommand and the Receiver, so there's not decoupling there.
why it is said it decouples the sender and the receiver
My copy of the book doesn't say that's the goal of the Command pattern:
Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.
Andrew's answer touches on the fact that the logic thread is decoupled from the commands. You can maybe better see the loose coupling between Invoker and Command when you refer to the sequence diagram of the pattern described in the Design Patterns:
Many design patterns define a Client that is loosely coupled from the variations (e.g., Visitor, Strategy, Observer, Iterator, etc.). Loose coupling is a benefit to maintainability, so-called design for change. Command is special, since the Client who's protected from changes is Invoker -- it is decoupled from ConcreteCommmand classes. I think that's the classic decoupling you're looking for. Adding new commands will require changing the Client, but shouldn't break Invoker, who only knows the Command abstraction.
I have always thought of the Command pattern as unique, because its main goal seems to be about providing functional requirements: undo, redo, logging, macro-command operations, transactions, etc.
Edit
Regarding IReceiver abstraction and decoupling from Client and concrete Receiver classes: that is possibly just the Strategy pattern being used with Command. I quoted the original book. Lots of variants of patterns exist (Wikipedia is not always a great reference for patterns because of this).
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.
This question already has answers here:
What is a callback method in Java? (Term seems to be used loosely)
(6 answers)
Closed 8 years ago.
I am reading the spring documentation. All the time I get this word "callback".
For example:
Lifecycle callbacks
Initialization callbacks etc.
How do we understand callback function ? And when you say "Lifecycle callbacks" in the spring, what does it mean ?
I have kept efforts in understanding this but I am not sure if I have understood correctly.
Please help.
LifeCycle
In the context of Spring beans (which I believe is the context of what you are reading - hard to tell with the little info you've provided), beans go through different lifecycle phases (like creation and destruction). Here are the lifecycle phases of the Spring bean you can hook into:
Callback
#R.T.'s wikipedia link to what a callback is, is a good starting point to understanding callbacks. In Java, the concept of callback is implemented differently.
In object-oriented programming languages without function-valued arguments, such as in Java before its 1.7 version, callbacks can be simulated by passing an instance of an abstract class or interface, of which the receiver will call one or more methods, while the calling end provides a concrete implementation.
A good example is given by #SotiriosDelamanolis in this answer, which I'll post here just for context.
/**
* #author #SotiriosDelamanolis
* see https://stackoverflow.com/a/19405498/2587435
*/
public class Test {
public static void main(String[] args) throws Exception {
new Test().doWork(new Callback() { // implementing class
#Override
public void call() {
System.out.println("callback called");
}
});
}
public void doWork(Callback callback) {
System.out.println("doing work");
callback.call();
}
public interface Callback {
void call();
}
}
LifeCycle Callback
By looking at the image above, you can see that Spring allows you to hook into the bean lifecyle with some interfaces and annotations. For example
Hooking into the bean creation part of the lifecycle, you can implements InitializingBean, which has a callback method afterPropertiesSet(). When you implements this interface, Spring pick up on it, and calls the afterPropertiesSet().
For example
public class SomeBean implements InitializingBean {
#Override
public void afterPropertiesSet() { // this is the callback method
// for the bean creation phase of the
// spring bean lifecycle
// do something after the properties are set during bean creation
}
}
Alternatively, you can use the #PostConstruct method for a non-InitializingBean implemented method, or using the init-method in xml config.
The diagram shows other lifecycle phases you can hook into and provide "callback" method for. The lifecycle phases are underlined at the top in the diagram
You can see more at Spring reference - Lifecycle Callbacks
The wiki has a good explanation:
In computer programming, a callback is a reference to executable code,
or a piece of executable code, that is passed as an argument to other
code. This allows a lower-level software layer to call a subroutine
(or function) defined in a higher-level layer.
Also check this interesting article Java Tip 10: Implement callback routines in Java
A sample example:
interface CallBack {
void methodToCallBack();
}
class CallBackImpl implements CallBack {
public void methodToCallBack() {
System.out.println("I've been called back");
}
}
class Caller {
public void register(CallBack callback) {
callback.methodToCallBack();
}
public static void main(String[] args) {
Caller caller = new Caller();
CallBack callBack = new CallBackImpl();
caller.register(callBack);
}
}
Paul Jakubik, Callback Implementations in C++.
Callbacks are most easily described in terms of the telephone system.
A function call is analogous to calling someone on a telephone, asking
her a question, getting an answer, and hanging up; adding a callback
changes the analogy so that after asking her a question, you also give
her your name and number so she can call you back with the answer.
In the following class:
public class Ignition {
private EngineManagementSystem mediator;
private boolean on;
public Ignition(EngineManagementSystem mediator) {
this.mediator = mediator;
on = false;
mediator.registerIgnition(this);
}
public void start() {
on = true;
mediator.ignitionTurnedOn();
System.out.println("Ignition turned on");
}
public void stop() {
on = false;
mediator.ignitionTurnedOff();
System.out.println("Ignition turned off");
}
public boolean isOn() {
return on;
}}
I am unsure of the reason for these lines of code, e.g:
mediator.ignitionTurnedOn();
Why does this class need to invoke this method to inform the mediator that the ignition is on? would this mean that the method is invoked twice? Once by this method and then within the mediator itself?
The purpose of the mediator is to relay information between colleagues. You only have to inform the mediator of things that other colleagues in your system need to know about.
I would venture that in this system, there is perhaps another class perhaps called Engine which has a start() method also registered with the mediator.
When the Ignition start method calls mediator.ignitionTurnedOn(), most likely, the mediator then calls something like getEngine().start() from inside its ignitionTurnedOn() method.
Probably nothing is invoked twice here.
The purpose of the mediator is to provide highly cohesive services that allow to decouple the elements of the system. In terms of a car, the Ignition system would not need to know the details of what happens, e.g., a Choke is opened, a Starter is invoked, etc. as these details can change depending on the type of Engine system.
So, here's what happens likely:
To know for sure, you'd have to see how :Ignition is being called and what Mediator.ignitionTurnedOn() actually does.
Can i attach java shutdown hook across jvm .
I mean can I attach shut down from my JVM to weblogic server running in different jvm?
The shutdown hook part is in Runtime.
The across JVM part you'll have to implement yourself, because only you know how your JVMs can discover and identify themselves.
It could be as simple as creating a listening socket at JVM1 startup, and sending port number of JVM2 to it. JVM1 would send shutdown notification to JVM2 (to that port) in its shutdown hook.
The short anser is: You can, but not out of the box and there are some pitfalls so please read the section pitfalls at the end.
A shutdown hook must be a thread object Runtime.addShutdownHook(Thread) that the jvm can access. Thus it must be instantiated within that jvm.
The only way I see to do it is to implement a Runnable that is also Serializable and some kind of remote service (e.g. RMI) which you can pass the SerializableRunnable. This service must then create a Thread pass the SerializableRunnable to that Thread's constructor and add it as a shutdown hook to the Runtime.
But there is also another problem in this case. The SerializableRunnable has no references to objects within the remote service's jvm and you have to find a way how that SerializableRunnable can obtain them or to get them injected. So you have the choice between a ServiceLocator or an
dependency injection mechanism. I will use the service locator pattern for the following examples.
I would suggest to define an interface like this:
public interface RemoteRunnable extends Runnable, Serializable {
/**
* Called after de-serialization from a remote invocation to give the
* RemoteRunnable a chance to obtain service references of the jvm it has
* been de-serialized in.
*/
public void initialize(ServiceLocator sl);
}
The remote service method could then look like this
public class RemoteShutdownHookService {
public void addShutdownhook(RemoteRunnable rr){
// Since an instance of a RemoteShutdownHookService is an object of the remote
// jvm, it can provide a mechanism that gives access to objects in that jvm.
// Either through a service locator
ServiceLocator sl = ...;
rr.initialize(sl);
// or a dependency injection.
// In case of a dependecy injection the initialize method of RemoteRunnable
// can be omitted.
// A short spring example:
//
// AutowireCapableBeanFactory beanFactory = .....;
// beanFactory.autowireBean(rr);
Runtime.getRuntime().addShutdownHook(new Thread(rr));
}
}
and your RemoteRunnable might look lioke this
public class SomeRemoteRunnable implements RemoteRunnable {
private static final long serialVersionUID = 1L;
private SomeServiceInterface someService;
#Override
public void run() {
// call someService on shutdown
someService.doSomething();
}
#Override
public void initialize(ServiceLocator sl) {
someService = sl.getService(SomeServiceInterface.class);
}
}
Pitfalls
There is only one problem with this approach that is not obvious. The RemoteRunnable implementation class must be available in the remote service's classpath. Thus you can not just create a new RemoteRunnable class and pass an instance of it to the remote service. You always have to add it to the remote JVMs classpath.
So this approach only makes sense if the RemoteRunnable implements an algorithm that can be configured by the state of the RemoteRunnable.
If you want to dynamically add arbitrary shutdown hook code to the remote JVM without the need to modify the remote JVMs classpath you must use a dynamic language and pass that script to the remote service, e.g. groovy.
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.