Related
What is the difference between the Strategy pattern and Polymorphism in Java?
I'm confused that whatever is achieved via Strategy Pattern is basically possible by polymorphism. Correct me if I'm wrong in this regard.
Please, also provide me example to eradicate my confusion.
For me, the link from CKing post and the example in Wikipedia are clear enough, but I'll try to give you a new example. As they said, Strategy Pattern is mostly a way to change the behaviour of an algorithm at runtime. Of course you can achieve this in many different ways (such as holding a value and using switch-case, but it wouldn't be as nice as Strategy Pattern).
Let's say you're developing a turn-based strategy game with two kind of Units: Infantry and Tank (subclasses of Unit). Your terrain could be Plains, Railroad or Forests.
class Unit{
MovementStrategy ms;
final int baseMovement;
int x,y;
public Unit(int baseMovement){
this.baseMovement = baseMovement;
}
abstract void fire();
void moveForward(){
x = x + ms.getHexagonsToMove(baseMovement);
}
void setMovementStrategy(MovementStrategy ms){
this.ms = ms;
}
}
Any Unit subclass must implement fire() method because it's going to be completely different for them (Tank shots heavy long-distance round and Infantry shot several short distance light bullets). In this example we use normal polymorphism/inheritance since fire() method will be really different for any unit, and it won't change during the game.
class Infantry extends Unit{
public Infantry(){
super(2);
}
void fire(){
//whatever
}
}
class Tank extends Unit{
public Tank(){
super(5);
}
void fire(){
//whatever
}
}
Units also are able to move, and have a field baseMovement that holds the number of hexagons it can walk. We're developing a strategy game, not a real world simulation, so we don't care how they move, we just want to add a value to their coordinates (in my example I only use X coordinate in order to get a simpler code). If all the terrain was the same, we wouldn't need any Strategy object... but we need to change the behaviour of move() method at runtime!
So, we implement a different MovementStrategy class for each of our kinds of Terrain, and we program our game to trigger a setMovementStrategy() to any unit that move on each hexagon. And we don't even need to write anything else in our Unit subclasses.
interface MovementStrategy{
public int getHexagonsToMove(int base);
}
class PlainMovementStrategy implements MovementStrategy{
public int getHexagonsToMove(int base){
return base;
}
}
class RailroadMovementStrategy implements MovementStrategy{
public int getHexagonsToMove(int base){
return base*3;
}
}
class ForestMovementStrategy implements MovementStrategy{
public int getHexagonsToMove(int base){
return (int)(base/2);
}
}
Now, when any Unit move inside a Forest, we call
unit.setMovementStrategy(new ForestMovementStrategy());
And as soon it goes to a Plain, we do:
unit.setMovementStrategy(new PlainMovementStrategy());
Now we're able to change how far away our units move depending on the Terrain, and we don't need to rewrite in any of the subclasses.
I hope this helps you a better understanding of the difference.
I'm confused that whatever is achieved via Strategy Pattern is basically possible by polymorphism.
You can't drive a car without a steering wheel. That does not mean that a steering wheel is a car. Similarly, the Strategy pattern relies on polymorphism but that does not mean that they are the same thing.
The purpose of the Strategy pattern is to promote the use of composition (has-a) over inheritance (is-a). Instead of your class inheriting behavior from a super class, you define the behavior in a separate class and your class has-a reference to it.
As far as an example goes, take a look at this answer that does a good job.
Basic difference : Polymorphism is programming language concept, and Strategy pattern is one of behavioral design pattern of GoF.
Polymorphism is the provision of a single interface for several different underlying data types.
Example: The steering wheel(i.e., the interface) is same no matter what type of actual steering mechanism is used. That is, the steering wheel works the same whether your car has manual steering, power steering, or rack-and-pinion steering. Therefore once you know how to operate the steering wheel, you can drive any type of car.
In programming, Polymorphism implemented in two ways:
Early-Binding/Static/Compile-Time Polymorphism (ex: function overloading)
Late-Binding/Dynamic/Run-Time Polymorphism (ex: function overriding)
A Strategy pattern defines a set of algorithms that can be used interchangeably.
The Strategy pattern is a dynamic pattern (How do you want run a behavior in software?).
Example of core java: java.util.Comparator#compare(), executed by among others Collections#sort().
Modes of transportation is analogous to strategy design pattern. We use car, bike, bus, local train and so on.. different strategies to go office day by day.
If you are establishing an analogy where:
in one case you have several overridable methods;
in the other case you have a Strategy interface with several implementations,
then the difference is the degree of coupling, which is very strong in the first case, whereas in the second case any foreign code can participate in your class's logic by contributing its Strategy implementation.
Q: What is the difference between the Strategy pattern and Polymorphism
in Java?
The questions is certainly confusing since initially there seems not to be any relation between these two ideas.
Polymorphism is a much broader concept in programming and yes the strategy pattern in Java uses a form of polymorphism catalogued as inclusion polymorphism to accomplish its intent, but this is by no means the only type of polymorphism that exists, neither it is the only way to implement the strategy pattern as I will demonstrate soon.
Also polymorphism is not something that only exists in Java or in object-oriented programming languages. Different forms of polymorphism exist in all the programming paradigms and not in all languages you are forced to use polymorphism to implement a strategy pattern (e.g. functional languages).
For further discussion on this topic please read this other answer where we have discussed whether polymorphism is possible without inheritance and I provide interesting references and examples to other types of polymorphism like parametric and ad-hoc polymorphism.
Ideally this will reveal to you that polymorphism is a bigger concept that goes beyond the boundaries of object-oriented programming and even beyond inheritance and subtyping.
Q: I'm confused that whatever is achieved via Strategy Pattern is
basically possible by polymorphism. Correct me if I'm wrong in this
regard.
From my point of view the relations between these two concepts are: that the strategy pattern leverages the power of polymorphism available in languages like Java to implement its intent, and that polymorphism can be considered in itself a pattern.
For instance, consider this quote from the GoF book:
If we assumed procedural languages, we might have included design
patterns called 'inheritance', 'encapsulation' and 'polymorphism'.
It is just that we rarely think of polymorphism as a pattern, first because it implies many things and because it is implemented differently in different languages and also because it typically presents as some form of language feature.
In his book Elemental Design Patterns, Jason Mc C. Smith comments on the GoF quote above saying:
Pattern are language-independent concepts; they take form and become
concrete solutions when you implement them within a particular
language with a given set of language features and constructs [...]
This means that it is a bit strange to talk about "Java design
pattern", "C++ design patterns", "Websphere design pattern" and so on,
even though we all do it. It's a mildly lazy form of shorthand for
what we really mean, or should mean: design patterns as implemented in
Java, C++, WebSphere and so on, regardless of language or API.
So, as you can see, you are thinking in the Strategy pattern from the perspective of the Java implementation, but in other language paradigms such pattern may have been implemented in different ways, probably without using inheritance at all, for example, in pure functional programming languages this is most certainly implemented using high order functions and function composition.
As such, this would be an strategy pattern implementation without resorting to inclusion polymorphism at all. In a function composition strategy we may still be using other forms of polymorphism (e.g. parametric), but that is not a requirement for the strategy pattern
Q: Please, also provide me example to eradicate my confusion.
As discussed above, in Java we are probably forced to use inclusion polymorphism to implement a Strategy pattern, but as explained above as well, patterns are not something that belong to a specific language, so if we think of the strategy pattern as a concept living outside any language boundaries then you will easily see other languages implement this in different ways.
In some hypothetical functional language I may have a function that reads some data from a file, maybe the file is encrypted and you need to provide a decryption strategy:
function readFile(path: String, decrypt: string -> string) {
return decrypt(loadFromDisk(path));
}
And that decrypt argument is a function that serves the purpose of a strategy pattern, it encapsulates an interchangeable algorithm.
Now you can do
readFile("customers.txt", aes)
readFile("finance.txt", blowfish)
Where aes and blowfish are decryption function strategies.
There are dozens of languages that work like this, SML, Haskell, JavaScript, etc.
First of all. Polymorphism can mean two different things. Most commonly polymorphism refers to a polymorphic type. However, you are asking for the pattern.
Polymorphic code can change itself each time it runs while the function of the code stays the same. An easy example is to do 1+3=4 instead of 5-1=4. Both achieves the same result using different code. This is useful for code that does not want to be recognized i.e computer viruses or cryptographic code.
Strategy pattern on the other hand uses a family of algorithms that can be interchanged. This might be used when translating text. First some code determines the language. if the language is swedish or spanish the text will be processed by, different functions of the same family, translateSwedish() or translateSpanish().
To round things up. Polymorphic code uses different code that achieves the same result. While Strategy uses different code to achieve better results.
Consider this
we have animals and a strategy pattern object to describe how they move...
for instance
fly/swim/walk
Given the large number of animals that use any of these methods (ie thousands of different animals fly), we need to use the same code for many different animals. That code should only exist in one place, so that it is easily changed and doesn't take up any unneeded space.
In this example, a straightforward polymorphism approach will result in massive code duplication. A more complex approach which places a intermediate class between animal and say robin fail to take in to consideration that how a animal moves is not really what defines it. Furthermore, it is possible that a animal has other strategy objects and they cannot all be made polymorphic through intermediate classes.
One definition for Polymorphism is the provision of a single interface to entities of different types.
With that in mind say you have a “bird” interface and all of your bird classes must implement “laysEggs()” method, well no biggie that works. And as you keep coding your “bird paradise program” you now add the “fly()” and realize that overloading and overriding for penguin and kiwi is unnecessary as in real life they can't fly, yet you must still implement that method. This can become tedious and pointless as you are faced with Ostrich and others that can't fly. And even worst off when adding the method “swim()” because even fewer birds can swim. As you may already know, the strategy pattern solves this problem.
In lame-man’s terms you can think of Polymorphism as a conglomerate of practices, while the Strategy Pattern is the best practice for a specific case. Example: the Strategy Pattern is to be used when an algorithm's behavior needs to be selected at Runtime (via interchangeable algorithms). And although it is sort of true that whatever is achieved via Strategy Pattern is basically possible by polymorphism, without knowledge of the Strategy Pattern this would leave you with the “reinvent the wheel” problem to solve this specific problem. In conclusion, they are very different even if one is based on the other.
I'll leave you to see “Ender Muab'Dib” code as it is well explained if you still want a code example from me just ask, cheers and hope I helped.
Polymorphism is a principle and Strategy is a design pattern
From oracle documentation page
The dictionary definition of polymorphism refers to a principle in biology in which an organism or species can have many different forms or stages. This principle can also be applied to object-oriented programming and languages like the Java language. Subclasses of a class can define their own unique behaviors and yet share some of the same functionality of the parent class.
Polymorphism can be achieved in compile time ( method overloading) and run time (method overriding).
Strategy_pattern
Defines a family of algorithms,
Encapsulates each algorithm, and
Makes the algorithms interchangeable within that family.
Strategy can use run-time polymorphism principle to achieve the desired functionality.
Strategy pattern had one more component called Context in it's URL diagram.
Refer to below SE posts:
Real World Example of the Strategy Pattern
Does this Java Strategy pattern have a redundant Context class?
Few more useful articles:
strategy by sourcemaking
Here is the concise response:
Polymorphism is one of the fundamental characteristics of
object-oriented programming.
Strategy pattern is a language-independent pattern that can be implemented by all
programming languages paradigms, such as imperative, functional, and
object-oriented.
Therefore, if you are going to implement Strategy pattern by using Java, that is OOP, then you just need to use polymorphism.
In other words, Strategy pattern is one of many forms of polymorphism.
EDIT
Even though I use a pseudo-Java syntax below for illustration, this question is NOT limited to any 1 programming language. Please feel free to post an idiom or language-provided mechanism from your favorite programming language.
When attempting to reuse an existing class, Old, via composition instead of inheritance, it is very tedious to first manually create a new interface out of the existing class, and then write forwarding functions in New. The exercise becomes especially wasteful if Old has tons of public methods in it and whereas you need to override only a handful of them.
Ignoring IDE's like Eclipse that though can help with this process but still cannot reduce the resulting verbosity of code that one has to read and maintain, it would greatly help to have a couple language mechanisms to...
automatically extract the public methods of Old, say, via an interfaceOf operator; and
by default forward all automatically generated interface methods of Old , say, via a forwardsTo operator, to a composed instance of Old, with you only providing definitions for the handful of methods you wish to override in New.
An example:
// A hypothetical, Java-like language
class Old {
public void a() { }
public void b() { }
public void c() { }
private void d() { }
protected void e() { }
// ...
}
class New implements interfaceOf Old {
public New() {
// This would auto-forward all Old methods to _composed
// except the ones overridden in New.
Old forwardsTo _composed;
}
// The only method of Old that is being overridden in New.
public void b() {
_composed.b();
}
private Old _composed;
}
My question is:
Is this possible at the code level (say, via some reusable design pattern, or idiom), so that the result is minimal verbosity in New and classes like New?
Are there any other languages where such mechanisms are provided?
EDIT
Now, I don't know these languages in detail but I'm hoping that 'Lispy' languages like Scheme, Lisp, Clojure won't disappoint here... for Lisp after all is a 'programmable programming language' (according to Paul Graham and perhaps others).
EDIT 2
I may not be the author of Old or may not want to change its source code, effectively wanting to use it as a blackbox.
This could be done in languages that allow you to specify a catch-all magic method (eg. __call() in php). You could catch any function call here that you have not specifically overriden, check if it exists in class Old and if it does, just forward the call.
Something like this:
public function __call($name, $args)
{
if (method_exists($old, $name))
{
call_user_func([$obj, $name], $args);
}
}
First, to answer the design question in the context of "OOP" (class-oriented) languages:
If you really need to replace Old with its complete interface IOld everywhere you use it, just to make New, which implements IOld, behave like you want, then you actually should use inheritance.
If you only need a small part of IOld for New, then you should only put that part into the interface ICommon and let both Old and New implement it. In this case, you would only replace Old by ICommon where both Old and New make sense.
Second, what can Common Lisp do for you in such a case?
Common Lisp is very different from Java and other class-oriented languages.
Just a few pointers: In Common Lisp, objects are primarily used to structure and categorize data, not code. You won't find "one class per file", "one file per class", or "package names completely correspond to directory structure" here. Methods do not "belong" to classes but to generic functions whose sole responsibility it is to dispatch according to the classes of their arguments (which has the nice side effect of enabling a seamless multiple dispatch). There is multiple inheritance. There are no interfaces as such. There is a much stronger tendency to use packages for modularity instead of just organizing classes. Which symbols are exported ("public" in Java parlance) is defined per package, not per class (which would not make sense with the above obviously).
I think that your problem would either completely disappear in a Common Lisp environment because your code is not forced into a class structure, or be quite naturally solved or expressed in terms of multiple dispatch and/or (maybe multiple) inheritance.
One would need at least a complete example and large parts of the surrounding system to even attempt a translation into Common Lisp idioms. You just write code so differently that it would not make any sense to try a one-to-one translation of a few forms.
I think Go has such a mechanism, a struct can embed methods from another struct.
Take a look here. This could be what you are asking as second question.
Each method in Facade Object is combination of several other methods exposed in several interfaces. Over the period of time this object will also grow as we will come to know about different operations that can be achieved by combining different interfaces available in complex system and its method.
My question is simple:
1) It is a better option to go ahead with Facade or do we have some other option available? because as we increase the number of methods to accommodate each new operation in Facade object, it also becomes complex. A possible solution that I can think of is to create one more Facade
2) Also, is there a limit-on methods exposed by facade when we will say it become complex?
Update: my analysis says stop adding more method to a Facade if it is making hard to understand and rethink your design; is that it?
Since your question is very abstract, it's hard to answer it in a way that is guaranteed to be good for the specifics of what you're writing.
As far as I can tell, the question you're asking is really, if you have
interface A { public void a(); }
interface B { public void b(); }
class ABFacade {
private final A a = ...
private final B b = ...
public void ab() { a.a(); b.b(); }
}
then is that useful or not?
The answer is going to depend on
The problem domain - how well defined is it?
How you name things - will people understand it?
Code reuse - is there more than one thing that will ever need to call a facade method?
I don't think there is a single right answer - at least not with specific examples. It also depends on what the purpose for using this pattern is - better code reuse? Fewer sets of duplicate code that does something complex? Creating choke points all code that does X must pass through? Clarity for other developers? The answers to that question profoundly affects what your code should look like.
I can suggest some general things that might help result in something useful:
If a facade method will only be used in one place, it probably does not deserve to be in the facade - if it the code only has one client, it probably makes more sense to do all the steps inline
Can some operation on the facade be given clear naming? Would the result be more intuitive to use than writing out everything the facade does? If so, then that probably should be on the facade
At the end, it's just a pattern. If it lets you write smaller, better or more reliable software, use it; if it doesn't, don't bother.
I know one of the goals of pure functional programming is to eliminate mutability, and therefore to preclude side-effects. But let's face it, Java is not a functional language even with all of the functional-programming libraries that exist. In fact it seems that some of the FP-libraries know and expect this. For instance in Functional Java, there is the Effect class. In the Jedi FP library, there is the Command interface. This allows you to -- among other things -- apply a command pattern with type-safety to elements of an Iterable without the nasty for-loop boilerplate.
Command<PhoneNumber> makeCall = new Command<PhoneNumber> {
public void execute(PhoneNumber p) { p.call(); }
}
List<PhoneNumber> phoneList = ...
FunctionalPrimitives.forEach( phoneList, makeCall );
So the question is, is there anything like that in Guava?
EDITED AFTER ANSWER ACCEPTED FOR CLARIFICATION
I am developing a framework that helps with the "vertical problem" inherent in most Java FP-libraries, under a certain set of circumstances. So I would not actually make the code example as shown above: i.e., explicitly declare a new class implementation of Command with all of its vertical-noise icky-ness, simply for the purpose of immediately applying it right after the declaration.
I was thinking more along the lines of the actual command pattern, where there may be several possible commands declared elsewhere, and only one of them gets passed into the code which wants to apply it iteratively. Furthermore, the goal of my framework is to make it more idiomatic to create functional-interface objects (functions, predicates, commands, other simple lambdas) without simply moving the vertical problem elsewhere. I have long realized this is not within the scope of Guava. But as Command-like interface are available in other FP libraries, I just wanted to know if an analog existed in Guava.
A more complete code example, using my framework, might be something like this:
class Stuff {
private final Stuff CALLS_TO = callsTo(Stuff.class); // a proxy
public static final Command<Stuff> CMD1 = commandFor(CALLS_TO.someMethod1());
public static final Command<Stuff> CMD2 = commandFor(CALLS_TO.someMethod2());
// methods exist for use elsewhere, but are conveniently also wrapped as commands
public void someMethod1() {...}
public void someMethod2() {...}
}
class Activity {
public void handleIt(List<Stuff> stuffs, Command<Stuff> doCmd) {
doSomeThings();
...
forEach(stuffs, doCmd);
...
doOtherThings();
}
}
Nope!
Kevin Bourrillion, the Guava project lead, has said on Guava's functional features:
“The syntax sucks. At the same time, this stuff is now, has always been and will always be nothing but a stopgap measure until the right language change can come along, at which time we can finally really decide on the optimal syntax and have functional-style programming start actually making lives better in Java for once. So I’m undecided how much effort to put into the Function/Predicate stuff; it’s in the library more because it sort of had to be, not so much because we think it’s a crown jewel.”
We will probably change our strategy significantly when Java 8 comes along, but that won't be for a while yet.
Also, we haven't found many use cases for which we think the Command interface you describe would be the best solution. For example, we think that your above code would be much better written as
for(PhoneNumber phone : phoneList) {
phone.call();
}
the old-fashioned way. We could potentially be convinced of the merit of Command, but I think the "for-each" use case is almost always better done the old-fashioned way.
I wonder what is the best way in terms of strict OOP to add functionality to built-in types like Strings or integers or more complex objects (in my case the BitSet class).
To be more specific - I got two scenarios:
Adding a md5 hashing method to the String object
Adding conversion methods (like fromByteArray() or toInteger()) to the BitSet class.
Now I wonder what the best practices for implementing this would be.
I could e.g. create a new Class "BitSetEx" extending from BitSet and add my methods. But I don't like the idea since this new class would need describing name and "BitSetWithConversionMethods" sound really silly.
Now I could write a class consisting only of static methods doing the conversions.
Well I got a lot of ideas but I wan't to know what would be the "best" in sense of OOP.
So could someone answer me this question?
There are a few approaches here:
Firstly, you could come up with a better name for the extends BitSet class. No, BitsetWithConversionMethods isn't a good name, but maybe something like ConvertibleBitSet is. Does that convey the intent and usage of the class? If so, it's a good name. Likewise you might have a HashableString (bearing in mind that you can't extend String, as Anthony points out in another answer). This approach of naming child classes with XableY (or XingY, like BufferingPort or SigningEmailSender) can sometimes be a useful one to describe the addition of new behaviour.
That said, I think there's a fair hint in your problem (not being able to find a name) that maybe this isn't a good design decision, and it's trying to do too much. It is generally a good design principle that a class should "do one thing". Obviously, depending on the level of abstraction, that can be stretched to include anything, but it's worth thinking about: do 'manipulating the set/unset state of a number of bits' and 'convert a bit pattern to another format' count as one thing? I'd argue that (especially with the hint that you're having a hard time coming up with a name) they're probably two different responsibilities. If so, having two classes will end up being cleaner, easier to maintain (another rule is that 'a class should have one reason to change'; one class to both manipulate + convert has at least 2 reasons to change), easier to test in isolation, etc.
So without knowing your design, I would suggest maybe two classes; in the BitSet example, have both a BitSet and (say) a BitSetConverter which is responsible for the conversion. If you wanted to get really fancy, perhaps even:
interface BitSetConverter<T> {
T convert(BitSet in);
BitSet parse(T in);
}
then you might have:
BitSetConverter<Integer> intConverter = ...;
Integer i = intConverter.convert(myBitSet);
BitSet new = intConverter.parse(12345);
which really isolates your changes, makes each different converter testable, etc.
(Of course, once you do that, you might like to look at guava and consider using a Function, e.g. a Function<BitSet, Integer> for one case, and Function<Integer, BitSet> for the other. Then you gain a whole ecosystem of Function-supporting code which may be useful)
I would go with the extending class. That is actually what you are doing, extending the current class with some extra methods.
As for the name: you should not name at for the new features, as you might add more later on. It is your extended BitSet class, so BitSetEx allready sounds better then the BitSetWithConversionMethods you propose.
You don't want to write a class with the static methods, this is like procedural programming in an OOP environment, and is considered wrong. You have an object that has certain methods (like the fromByteArray() you want to make) so you want those methods to be in that class. Extending is the way to go.
It depends. As nanne pointed out, subclass is an option. But only sometimes. Strings are declared final, so you cannot create a subclass. You have at least 2 other options:
1) Use 'encapsulation', i.e. create a class MyString which has a String on which it operates (as opposed to extending String, which you cannot do). Basically a wrapper around the String that adds your functionality.
2) Create a utility/helper, i.e. a class with only static methods that operate on Strings. So something like
class OurStringUtil {
....
public static int getMd5Hash(String string) {...}
....
}
Take a look at the Apache StringUtils stuff, it follows this approach; it's wonderful.
"Best way" is kinda subjective. And keep in mind that String is a final class, so you can't extend it.
Two possible approaches are writing wrappers such as StringWrapper(String) with your extra methods, or some kind of StringUtils class full of static methods (since Java 5, static methods can be imported if you wan't to use the util class directly).