I am learning command design pattern. As far as I know, four terms always associated with the command pattern are command, receiver, invoker and client.
A concrete command class has an execute() method and the invoker has a couple of commands. The invoker decides when to call the execute() method of a command.
When the execute() method is called, it calls a method of the receiver. Then, the receiver does the work.
I don't understand why do we need the receiver class? We can do the work inside execute() method, it seems that the receiver class is redundant.
Thank in advance.
Design patterns are used to solve software problems.
You have to understand the problem before trying to understand the solution (in this case Command pattern)
The problems which command pattern apply are in the context of an object A (client) invoking a method in an object B (receiver), so the Receiver is part of the problem, not part of the solution.
The solution or idea that command pattern offers is to encapsulate the method invocation from A to B in an object (Command), in fact this is close to the formal pattern definition. When you manage a request as an object you are able to solve some problems or to implement some features. (you also will need other pieces like the one called Invoker)
This list can give you some good examples of what kind of problems o features are suitable for command pattern.
note: Comamnd pattern is not necesary about decoupling, in fact the most common example pattern immplementation, the client needs to make a new instance of the receiver so we cannot talk about decoupling here.
Imagine a class that can do couple of things, like Duck, it can eat and quack. Duck is a receiver in this example. To apply command pattern here, you need to be able to wrap eating and quacking into a command. They should be separate classes that derive from Command base class with execute() method because Duck can have only single execute() method. So EatCommand.execute() calls Duck.eat() and QuackCommand.execute() calls Duck.quack().
The goal of the command pattern is to decouple the invoker from the receiver.
The receiver must do the work ,not the command itself , the command just knows what is the receiver method to call, or the command can execute other commands . With the command pattern the invoker doesnt know what is being called expect for the command.
So a command can be reused by many invokers to execute the same action on the receiver.
Short answer is depends. This is not based on my opinion alone. From GOF, Command Pattern, Implementation (page 238)
"How intelligent should a command be? A command can have a wide range of abilities. At one extreme it merely defines a binding between a receiver and the actions that carry out the request. At the other extreme it implements everything itself without delegating to a receiver at all. The latter extreme is useful when you want to define commands that are independent of existing classes, when no suitable receiver exists, or when a command knows its receiver implicitly. For example, a command that creates another application window may be just as capable of creating the window as any other object."
So I do not think one should create a receiver class just for the sake of it, or because most example say so. Create it only if there is a real need. One such case is when a class that acts as a receiver already exists as a separate class. If you have to write the code that is going to be invoked/executed and see no reason to create a separate class for that, then I do not see any fault in adding the invoker code to Command itself.
Related
I am generating a class in ByteBuddy.
As part of one method implementation, I would like to set a (let's just say) public instance field in another object to the return value of a MethodCall invocation. (Keeping the example public means that access checks etc. are irrelevant.)
I thought I could use MethodCall#setsField(FieldDescription) to do this.
But from my prior question related to this I learned that MethodCall#setsField(FieldDescription) is intended to work only on fields of the instrumented type, and, looking at it now, I'm not entirely sure why or how I thought it was ever going to work.
So: is there a way for a ByteBuddy-generated method implementation to set an instance field of another object to the return value of a method invocation?
If it matters, the "instrumented method" (in ByteBuddy's terminology) accepts the object whose field I want to set as an argument. Naïvely I'd expect to be able to do something like:
MethodCall.invoke(someMethod).setsField(somePublicField).onArgument(2);
There may be problems here that I am not seeing but I was slightly surprised not to see this DSL option. (It may not exist for perfectly good reasons; I just don't know what they would be.)
This is not possible as of Byte Buddy 1.10.18, the mechanism was originally created to support getters/setters when defining beans, for example. That said, it would not be difficult to add; I think it would even be easiest to allow any custom byte code to be dispatched as a consumer of the method call.
I will look into how this can be done, but as a new feature, this will take some time before I find the empty space to do so. The change is tracked on GitHub.
I found this line in an old branch and, as I have a lot of respect for the (unreachable) author, I'm trying to make sense of one specific line, more precisely the lambda at the end:
container.Register(Of ServiceStack.Configuration.IResolver)(Function(x) x)
container is a Funq.Container through ServiceStack. The intellisense tells me that the lambda is filling in for a (factory As Func(Of Funq.Container, ServiceStack.Configuration.IResolver)).
There is two things that I can assume about the author: he's better coder than I am, and he may have left this unfinished. For now I'm guessing that this lambda was deliberate and not some unfinished line with no clear intent, but so far nobody could help me understand why.
The container is a dependency injection container. Code elsewhere will ask the container for instances of interfaces. The code here is registration code, which is telling the container how to provide an IResolver. Furthermore, it's designed to accept a factory function; resolution later will call the function to product the requested IResolver.
In this case, it appears that the container itself implements IResolver. The lambda is a function that returns its argument, so it's trivial; its argument is a Funq.Container and it returns a ServiceStack.Configuration.IResolver, so the only way this can compile is if the container implements that interface.
Thus: The container implements IResolver. The code registers a factory function which always returns back the container itself when called.
It seems rather odd to do. I don't know ServiceStack at all, so I'm not sure why it's done this way.
There's a solid chance I'm misusing classes here which is why I need your help.
I've started developing with Java EE and one of the problems I am facing is I have a process which I have organised in a class, call it: "SendEmail.java".
Now let's say I have two other classes called "Thunderalert.java" and "FloodAlert.java" which will use all the methods that SendEmails.java has within it.
So I want to know the best way of using the SendEmails methods from each of the other classes.
Should I be creating an instance of SendEmails and accessing each method individually and error checking along the way (what if an exception is thrown?).. It's methods are just procedural code, so it's not really an 'object' as such
Shall I just be using the one method that runs all the other internal ones from within SendMail
Should this SendMail be redesigned as a helper class-type design?
I'm still quite new at Java EE so I'm not sure if there are any options available which I am missing
I think you should have one public method inside SendEmail class.
Btw, I would consider changing its name. I think having method send() when class is called SendEmail is not the best way (not to mention about names like call(), invoke() etc).
This is great article about this problem (The Kingdom of Nouns) in java.
What about something like: new Email(recipient, body).send()?
Or if you want to do it in a service style, I'd call it for example MailService
This question already has answers here:
What is reflection and why is it useful?
(23 answers)
Closed 6 years ago.
I was just curious, why should we use reflection in the first place?
// Without reflection
Foo foo = new Foo();
foo.hello();
// With reflection
Class cls = Class.forName("Foo");
Object foo = cls.newInstance();
Method method = cls.getMethod("hello", null);
method.invoke(foo, null);
We can simply create an object and call the class's method, but why do the same using forName, newInstance and getMthod functions?
To make everything dynamic?
Simply put: because sometimes you don't know either the "Foo" or "hello" parts at compile time.
The vast majority of the time you do know this, so it's not worth using reflection. Just occasionally, however, you don't - and at that point, reflection is all you can turn to.
As an example, protocol buffers allows you to generate code which either contains full statically-typed code for reading and writing messages, or it generates just enough so that the rest can be done by reflection: in the reflection case, the load/save code has to get and set properties via reflection - it knows the names of the properties involved due to the message descriptor. This is much (much) slower but results in considerably less code being generated.
Another example would be dependency injection, where the names of the types used for the dependencies are often provided in configuration files: the DI framework then has to use reflection to construct all the components involved, finding constructors and/or properties along the way.
It is used whenever you (=your method/your class) doesn't know at compile time the type should instantiate or the method it should invoke.
Also, many frameworks use reflection to analyze and use your objects. For example:
hibernate/nhibernate (and any object-relational mapper) use reflection to inspect all the properties of your classes so that it is able to update them or use them when executing database operations
you may want to make it configurable which method of a user-defined class is executed by default by your application. The configured value is String, and you can get the target class, get the method that has the configured name, and invoke it, without knowing it at compile time.
parsing annotations is done by reflection
A typical usage is a plug-in mechanism, which supports classes (usually implementations of interfaces) that are unknown at compile time.
You can use reflection for automating any process that could usefully use a list of the object's methods and/or properties. If you've ever spent time writing code that does roughly the same thing on each of an object's fields in turn -- the obvious way of saving and loading data often works like that -- then that's something reflection could do for you automatically.
The most common applications are probably these three:
Serialization (see, e.g., .NET's XmlSerializer)
Generation of widgets for editing objects' properties (e.g., Xcode's Interface Builder, .NET's dialog designer)
Factories that create objects with arbitrary dependencies by examining the classes for constructors and supplying suitable objects on creation (e.g., any dependency injection framework)
Using reflection, you can very easily write configurations that detail methods/fields in text, and the framework using these can read a text description of the field and find the real corresponding field.
e.g. JXPath allows you to navigate objects like this:
//company[#name='Sun']/address
so JXPath will look for a method getCompany() (corresponding to company), a field in that called name etc.
You'll find this in lots of frameworks in Java e.g. JavaBeans, Spring etc.
It's useful for things like serialization and object-relational mapping. You can write a generic function to serialize an object by using reflection to get all of an object's properties. In C++, you'd have to write a separate function for every class.
I have used it in some validation classes before, where I passed a large, complex data structure in the constructor and then ran a zillion (couple hundred really) methods to check the validity of the data. All of my validation methods were private and returned booleans so I made one "validate" method you could call which used reflection to invoke all the private methods in the class than returned booleans.
This made the validate method more concise (didn't need to enumerate each little method) and garuanteed all the methods were being run (e.g. someone writes a new validation rule and forgets to call it in the main method).
After changing to use reflection I didn't notice any meaningful loss in performance, and the code was easier to maintain.
in addition to Jons answer, another usage is to be able to "dip your toe in the water" to test if a given facility is present in the JVM.
Under OS X a java application looks nicer if some Apple-provided classes are called. The easiest way to test if these classes are present, is to test with reflection first
some times you need to create a object of class on fly or from some other place not a java code (e.g jsp). at that time reflection is useful.
I created a class, and in that class I have a method 'sendMessage: to: withArgs:' which recieves an object, a message and an array of arguments.
The method is used to send messages to object and perform some algorithm.
To use this method I have to create an instance x of the class I created and do something like x sendMessage: '+' to: '7' withArgs: '#(5)'.
The result of this sending the message '+' to the object 7 with the parameter 5, plus some stuff that my algorithm does. But what I want is that the algorithm will be used in every method call, meaning 7+5 will call my 'sendMessage: to: withArgs:'.
How can I do that? Or at least, Is there something called in each method sent to every object?
It's kinda funny, we were just discussing that in the Squeak irc channel. Take a peek at ObjectViewer, perhaps.
In your example, you want to intercept the message sends to a SmallInteger. Funnily enough, ObjectViewer works with very much every class BUT SmallInteger.
So, to intercept message sends to myObject, do this.
Create class Intercepter, let it inherit from ObjectTracer, perhaps. Change doesNotUnderstand to something that serves you:
doesNotUnderstand: aMessage
"do Mojo to aMessage as you describe it"
Then, to get your stuff going, create your Intercepter:
myIntercepter := Intercepter on: myObject.
And then
myObject become: myInterceptor.
In Squeak, see the class ObjectTracer. The class comment describes how to use it. You should be able to accomplish what you need with that, or at least using that as a model.
Have a look at the Reflectivity.
Unfortunately some of the paper links are not working, and I don't remember the exact invocation from the top of my head, but it's really easy to instrument code as you want, and even do it at runtime. Look for examples using class Link.
You can use method wrappers. To see what method wrappers are you can look for a paper called "Wrappers to the rescue". I think there is a package for squeak that already implements method wrappers.
In addition, you can see how a test code coverage analysis is made in the last version of Pharo because it uses a kind of method wrapper to see what methods are evaluated during a test run.
cheers,
Gaboto