Design Pattern : Applying behavior on objects of different family - java

I have a set of classes from third party library which I don't have access to the source. I need to add some common behavior on these objects by using a design pattern. How do I apply Decorator or Visitor pattern to these objects?
These objects have no common base class. These are either plain objects or having uncommon interfaces. I cannot add a common interface to these classes because these classes are not part of my project.
How do I add common behavior to these classes without checking ‘instance of’ in a single method.

To work with Decorator you need some well defined interface. So the first task is to find an interface. As third party classes dont have an interface, Adapter pattern comes to rescue. You can define your own interface and adapt the third party classes to interfaces you require them to adhere to.
class YourTypeAdapter implements YourAdapterInterface{
private Type instance; //need to adapt this as no interface present
public void interfaceMethod(){
instance.someTypeSpecificMethod();
//perform extra steps here
}
}
In this way you can adapt those Types which do not have a common interface into a suitable interface hierarchy for you. You can also add additional functionality that you want to add to this adapter. Or you can go ahead and use a decorator to YourTypeAdapter as now you have an interface YourAdapterInterface to work with.
References:
- OODesign Adapter pattern

Related

Marker interface vs empty abstract class

I am facing difficulties to decide between using a marker interface or an empty abstract class.
I have two classes BrokerResponse and Notification, which have no structural similarity. The only thing connecting them is the need to be subscribable for.
void register(Receivable receivable, BrokerObserver observer)
I somehow dislike using a Marker Interface, because it violates the basic definition of an Interface. On the other hand using an abstract super class would make me as uncomfortable, because both classes have no relationship with one another.
What is the generally preferable approach in this scenario and why?
Edit 1
I forgot to mention, that BrokerResponse is an abstract class itself, that has several subclasses to determine the respective type.
Abstract class vs. marker interface:
There is nothing wrong with marker interface and there are some use cases for it. Choosing between those two, marker interface has more flexibility.
If you do want to define a type, do use an interface.
An abstract class’s purpose is to provide an appropriate superclass from which other classes can inherit and thus share a common design - your classes don't have common design and nothing to share. Moreover you will stick both of them to some restricted design and will be not so flexible if you will need to add a real different parents to them in the future.
List of use-cases for abstract class:
Share code among several closely related classes.
Classes that extend your abstract class have many common methods or
fields or require access modifiers other than public (such as
protected and private).
Declare non-static or non-final fields what enables you to define
methods that can access and modify the state of the object to which
they belong.
Use-cases for interface:
Unrelated classes would implement your interface.
Specify the behavior of a particular data type, without concerning
who implements its behavior.
Advantage of multiple inheritances.
All listed arguments are for the usage of interface. Since BrokerResponse is abstract itself and has it's own hierarchy, making the fact that those classes don't have something in common more stronger.
As alternative you can use marker annotation. I would consider to stick one of those two approaches instead of Abstract Class.
Marker interface vs. marker annotation:
According to Joshua Bloch's 'Effective java':
Marker interfaces have two advantages over marker annotations. First
and foremost, marker interfaces define a type that is implemented by
instances of the marked class; marker annotations do not. The
existence of this type allows you to catch errors at compile time that
you couldn’t catch until runtime if you used a marker annotation.
Another advantage of marker interfaces over marker annotations is that
they can be targeted more precisely.
When should you use a marker annotation?
you must use an annotation if the marker applies to any program
element other than a class or interface, as only classes and
interfaces can be made to implement or extend an interface.
When should you use a marker interface?
Ask yourself the question, Might I want to write one or more methods
that accept only objects that have this marking? If so, you should use
a marker interface in preference to an annotation. This will make it possible
for you to use the interface as a parameter type for the methods in
question, which will result in the very real benefit of compile-time
type checking.
Summary:
If you want to define a type that does not have any new methods
associated with it, a marker interface is the way to go.
If you want to mark program elements other than classes and
interfaces, to allow for the possibility of adding more information to
the marker in the future, or to fit the marker into a framework that
already makes heavy use of annotation types, then a marker annotation
is the correct choice.
Using empty abstract class does not make any sense in this case as there is no multiple inheritance in Java.
Making you class implement some marker interface does not change you class hierarchy, it just marks your class with some additional metadata.
Image the case when your class which already is marked as Subscribable should also be for example Writable. If you use empty abstract class you will need to redesign the entire hierarchy. With marker interface it is just as easy as to add Writable to list of implementations.
How about annotating them? You got your answer that using a mark interface is the way to go here if you would have to choose, but using an annotation depending on what you might need to do would be much cleaner.
The fact that you say you need to make them somehow "the same" talks about an instanceof call and doing something based on that. The same thing could be achieved via isAnnotationPresent or the like.
But if you add a marker interface, how about making it not a marker interface - only in case you have a finite number of classes you need to test against? Something along the lines of MyInterface {boolean isSubscribable();}

Can I create a non-abstract method in an interface that will be called by every implementation? [duplicate]

I was asked a question, I wanted to get my answer reviewed here.
Q: In which scenario it is more appropriate to extend an abstract class rather than implementing the interface(s)?
A: If we are using template method design pattern.
Am I correct ?
I am sorry if I was not able to state the question clearly.
I know the basic difference between abstract class and interface.
1) use abstract class when the requirement is such that we need to implement the same functionality in every subclass for a specific operation (implement the method) and different functionality for some other operations (only method signatures)
2) use interface if you need to put the signature to be same (and implementation different) so that you can comply with interface implementation
3) we can extend max of one abstract class, but can implement more than one interface
Reiterating the question: Are there any other scenarios, besides those mentioned above, where specifically we require to use abstract class (one is see is template method design pattern is conceptually based on this only)?
Interface vs. Abstract class
Choosing between these two really depends on what you want to do, but luckily for us, Erich Gamma can help us a bit.
As always there is a trade-off, an interface gives you freedom with regard to the base class, an abstract class gives you the freedom to add new methods later. – Erich Gamma
You can’t go and change an Interface without having to change a lot of other things in your code, so the only way to avoid this would be to create a whole new Interface, which might not always be a good thing.
Abstract classes should primarily be used for objects that are closely related. Interfaces are better at providing common functionality for unrelated classes.
When To Use Interfaces
An interface allows somebody to start from scratch to implement your interface or implement your interface in some other code whose original or primary purpose was quite different from your interface. To them, your interface is only incidental, something that have to add on to the their code to be able to use your package. The disadvantage is every method in the interface must be public. You might not want to expose everything.
When To Use Abstract classes
An abstract class, in contrast, provides more structure. It usually defines some default implementations and provides some tools useful for a full implementation. The catch is, code using it must use your class as the base. That may be highly inconvenient if the other programmers wanting to use your package have already developed their own class hierarchy independently. In Java, a class can inherit from only one base class.
When to Use Both
You can offer the best of both worlds, an interface and an abstract class. Implementors can ignore your abstract class if they choose. The only drawback of doing that is calling methods via their interface name is slightly slower than calling them via their abstract class name.
reiterating the question: there is any other scenario besides these
mentioned above where specifically we require to use abstract class
(one is see is template method design pattern is conceptually based on
this only)
Yes, if you use JAXB. It does not like interfaces. You should either use abstract classes or work around this limitation with generics.
From a personal blog post:
Interface:
A class can implement multiple interfaces
An interface cannot provide any code at all
An interface can only define public static final constants
An interface cannot define instance variables
Adding a new method has ripple effects on implementing classes (design maintenance)
JAXB cannot deal with interfaces
An interface cannot extends or implement an abstract class
All interface methods are public
In general, interfaces should be used to define contracts (what is to be achieved, not how to achieve it).
Abstract Class:
A class can extend at most one abstract class
An abstract class can contain code
An abstract class can define both static and instance constants (final)
An abstract class can define instance variables
Modification of existing abstract class code has ripple effects on extending classes (implementation maintenance)
Adding a new method to an abstract class has no ripple effect on extending classes
An abstract class can implement an interface
Abstract classes can implement private and protected methods
Abstract classes should be used for (partial) implementation. They can be a mean to restrain the way API contracts should be implemented.
Interface is used when you have scenario that all classes has same structure but totally have different functionality.
Abstract class is used when you have scenario that all classes has same structure but some same and some different functionality.
Take a look the article : http://shoaibmk.blogspot.com/2011/09/abstract-class-is-class-which-cannot-be.html
There are a lot of great answers here, but I often find using BOTH interfaces and abstract classes is the best route. Consider this contrived example:
You're a software developer at an investment bank, and need to build a system that places orders into a market. Your interface captures the most general idea of what a trading system does,
1) Trading system places orders
2) Trading system receives acknowledgements
and can be captured in an interface, ITradeSystem
public interface ITradeSystem{
public void placeOrder(IOrder order);
public void ackOrder(IOrder order);
}
Now engineers working at the sales desk and along other business lines can start to interface with your system to add order placement functionality to their existing apps. And you haven't even started building yet! This is the power of interfaces.
So you go ahead and build the system for stock traders; they've heard that your system has a feature to find cheap stocks and are very eager to try it out! You capture this behavior in a method called findGoodDeals(), but also realize there's a lot of messy stuff that's involved in connecting to the markets. For example, you have to open a SocketChannel,
public class StockTradeSystem implements ITradeSystem{
#Override
public void placeOrder(IOrder order);
getMarket().place(order);
#Override
public void ackOrder(IOrder order);
System.out.println("Order received" + order);
private void connectToMarket();
SocketChannel sock = Socket.open();
sock.bind(marketAddress);
<LOTS MORE MESSY CODE>
}
public void findGoodDeals();
deals = <apply magic wizardry>
System.out.println("The best stocks to buy are: " + deals);
}
The concrete implementations are going to have lots of these messy methods like connectToMarket(), but findGoodDeals() is all the traders actually care about.
Now here's where abstract classes come into play. Your boss informs you that currency traders also want to use your system. And looking at currency markets, you see the plumbing is nearly identical to stock markets. In fact, connectToMarket() can be reused verbatim to connect to foreign exchange markets. However, findGoodDeals() is a much different concept in the currency arena. So before you pass off the codebase to the foreign exchange wiz kid across the ocean, you first refactor into an abstract class, leaving findGoodDeals() unimplmented
public abstract class ABCTradeSystem implements ITradeSystem{
public abstract void findGoodDeals();
#Override
public void placeOrder(IOrder order);
getMarket().place(order);
#Override
public void ackOrder(IOrder order);
System.out.println("Order received" + order);
private void connectToMarket();
SocketChannel sock = Socket.open();
sock.bind(marketAddress);
<LOTS MORE MESSY CODE>
}
Your stock trading system implements findGoodDeals() as you've already defined,
public class StockTradeSystem extends ABCTradeSystem{
public void findGoodDeals();
deals = <apply magic wizardry>
System.out.println("The best stocks to buy are: " + deals);
}
but now the FX whiz kid can build her system by simply providing an implementation of findGoodDeals() for currencies; she doesn't have to reimplement socket connections or even the interface methods!
public class CurrencyTradeSystem extends ABCTradeSystem{
public void findGoodDeals();
ccys = <Genius stuff to find undervalued currencies>
System.out.println("The best FX spot rates are: " + ccys);
}
Programming to an interface is powerful, but similar applications often re-implement methods in nearly identical ways. Using an abstract class avoids reimplmentations, while preserving the power of the interface.
Note: one may wonder why findGreatDeals() isn't part of the interface. Remember, the interface defines the most general components of a trading system. Another engineer may develop a COMPLETELY DIFFERENT trading system, where they don't care about finding good deals. The interface guarantees that the sales desk can interface to their system as well, so it's preferable not to entangle your interface with application concepts like "great deals".
Which should you use, abstract classes or interfaces?
Consider using abstract classes if any of these statements apply to your use case:
You want to share code among several closely related classes.
You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.
Consider using interfaces if any of these statements apply to your use case:
You expect that unrelated classes would implement your interface.
For example, the interfaces Comparable and Cloneable are implemented by many unrelated classes.
You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.
You want to take advantage of multiple inheritance of type.
New methods added regularly to interface by providers, to avoid issues extend Abstract class instead of interface.
http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
Things have been changed a lot in last three years with addition of new capabilities to interface with Java 8 release.
From oracle documentation page on interface:
An interface is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods.
As you quoted in your question, abstract class is best fit for template method pattern where you have to create skeleton. Interface cant be used here.
One more consideration to prefer abstract class over interface:
You don't have implementation in base class and only sub-classes have to define their own implementation. You need abstract class instead of interface since you want to share state with sub-classes.
Abstract class establishes "is a" relation between related classes and interface provides "has a" capability between unrelated classes.
Regarding second part of your question, which is valid for most of the programming languages including java prior to java-8 release
As always there is a trade-off, an interface gives you freedom with regard to the base class, an abstract class gives you the freedom to add new methods later. – Erich Gamma
You can’t go and change an Interface without having to change a lot of other things in your code
If you prefer abstract class to interface earlier with above two considerations, you have to re-think now as default methods have added powerful capabilities to interfaces.
Default methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older versions of those interfaces.
To select one of them between interface and abstract class, oracle documentation page quote that:
Abstract classes are similar to interfaces. You cannot instantiate them, and they may contain a mix of methods declared with or without an implementation. However, with abstract classes, you can declare fields that are not static and final, and define public, protected, and private concrete methods.
With interfaces, all fields are automatically public, static, and final, and all methods that you declare or define (as default methods) are public. In addition, you can extend only one class, whether or not it is abstract, whereas you can implement any number of interfaces.
Refer to these related questions fore more details:
Interface vs Abstract Class (general OO)
How should I have explained the difference between an Interface and an Abstract class?
In summary : The balance is tilting more towards interfaces now.
Are there any other scenarios, besides those mentioned above, where specifically we require to use abstract class (one is see is template method design pattern is conceptually based on this only)?
Some design patterns use abstract classes (over interfaces) apart from Template method pattern.
Creational patterns:
Abstract_factory_pattern
Structural patterns:
Decorator_pattern
Behavioral patterns:
Mediator_pattern
You are not correct. There are many scenarios. It just isn't possible to reduce it to a single 8-word rule.
The shortest answer is, extend abstract class when some of the functionalities uou seek are already implemented in it.
If you implement the interface you have to implement all the method. But for abstract class number of methods you need to implement might be fewer.
In template design pattern there must be a behavior defined. This behavior depends on other methods which are abstract. By making sub class and defining those methods you actually define the main behavior. The underlying behavior can not be in a interface as interface does not define anything, it just declares. So a template design pattern always comes with an abstract class. If you want to keep the flow of the behavior intact you must extend the abstract class but don't override the main behavior.
In my opinion, the basic difference is that an interface can't contain non-abstract methods while an abstract class can.
So if subclasses share a common behavior, this behavior can be implemented in the superclass and thus inherited in the subclasses
Also, I quoted the following from "software architecture design patterns in java" book
" In the Java programming language, there is no support for multiple inheritance.
That means a class can inherit only from one single class. Hence inheritance
should be used only when it is absolutely necessary. Whenever possible, methods
denoting the common behavior should be declared in the form of a Java interface to be implemented by different implementer classes. But interfaces suffer from the limitation that they cannot provide method implementations. This means that every implementer of an interface must explicitly implement all methods declared in an interface, even when some of these methods represent the invariable part of the functionality and have exactly the same implementation in all of the implementer classes. This leads to redundant code. The following example demonstrates how the Abstract Parent Class pattern can be used in such cases without requiring redundant method implementations."
Abstract classes are different from interfaces in two important aspects
they provide default implementation for chosen methods (that is covered by your answer)
abstract classes can have state (instance variables) - so this is one more situation you want to use them in place of interfaces
This is a good question The two of these are not similar but can be use for some of the same reason, like a rewrite. When creating it is best to use Interface. When it comes down to class, it is good for debugging.
This is my understanding, hope this helps
Abstract classes:
Can have member variables that are inherited (can’t be done in interfaces)
Can have constructors (interfaces can’t)
Its methods can have any visibility (ie: private, protected, etc - whereas all interface methods are public)
Can have defined methods (methods with an implementation)
Interfaces:
Can have variables, but they are all public static final variables
constant values that never change with a static scope
non static variables require an instance, and you can’t instantiate an interface
All methods are abstract (no code in abstract methods)
all code has to be actually written in the class that implements the particular interface
Usage of abstract and interface:
One has "Is-A-Relationship" and another one has "Has-A-Relationship"
The default properties has set in abstract and extra properties can be expressed through interface.
Example: --> In the human beings we have some default properties that are eating, sleeping etc. but if anyone has any other curricular activities like swimming, playing etc those could be expressed by Interface.
Abstract classes should be extended when you want to some common behavior to get extended. The Abstract super class will have the common behavior and will define abstract method/specific behavior which sub classes should implement.
Interfaces allows you to change the implementation anytime allowing the interface to be intact.
I think the answers here are missing the main point:
Java interfaces (the question is about Java but there are similar mechanisms in other languages) is a way to partially support multiple inheritance, i.e. method-only inheritance.
It is similar to PHP's traits or Python's duck typing.
Besides that, there is nothing additional that you truly need an interface for --and you cannot instantiate a Java interface.

How to achieve multiple inheritance in java

I am designing Traveller App. For which I need to design 'Traveller' class and with its instance I should be able to access properties of different types of Travel modes.
class Traveller {
// common properties.
}
class RoadTravel {
// properties specific to class
}
class WaterTravel {
// properties specific to class
}
class RailTravel {
// properties specific to class
}
from the above code , I just want to create instance of 'Traveller' class and should be able to access the properties of all other classes (RoadTravel,WaterTravel,RailTravel).
I dont want to create any dependency on my sub classes and also my instance variables should not be final.
Please suggest good way of implementation so that it should be easy to add any new type of Travel mode in future.
In Java you cannot have a class which extends (inherits) from multiple classes. (You might want to look into the Deadly Diamond of Death Problem.
In your case, what you could have would be a Travel interface which defines the behaviour each of your travel types need to expose, such as cost(int duration), getName(). etc/
Your logic would then use the Travel interface to do it's logic. The travel type dependent logic would be stored in the seperate classes which make use of the Travel interface. Your main logic would then delegate travel specific logic to these classes which are passed to it at run time.
You will need to take a look at the Strategy Design Pattern to see how you can implement this.
A way to implement multiple inheritance in java is the use of proxies.
Your requirements do not seem very clear and so I cannot suggest a complete solution.
If you provide an example of client code that will use these classes, I can suggest in more details how to implement it using proxies.

With the advent of default methods in Java8's Interfaces are class adapters now possible in Java

Class Adapters uptil now have been considered not possible in java.Previous question regarding the same also says so.
But, Java 8 now supports default methods in Interfaces and multiple interfaces can be implemented by a class.
So, a class inheriting from multiple interfaces with multiple default methods can make one interface's default methods act as an adapter and make a call to the other interface's (adaptee's) default method.
So, now is the statement Java 8 supports Class Adapters correct?
As far as I understood, the Class Adapter Pattern is about creating a class which extends multiple types so that it inherits at least one implementation and at least one interface not formerly directly implemented by the implementation to enable using the existing implementation via the interface.
This has been possible in Java, with the restriction that the Adapter can only inherit one implementation (class) but inherit multiple interfaces (Compare with this answer). This limitation hasn’t changed in any way. You still can only inherit from one class.
It is correct that interfaces can now have default methods, but this doesn’t change the abstract nature of an interface and doesn’t make them eligible for conceptually bearing an implementation.
Even if an interface contains only default methods (no abstract methods), you still can’t instantiate it without creating a new class which implements the interface. Such a strange interface could only exist for primarily supporting the creation of Adapter classes which would then not be an example of the Class Adapter Pattern anymore, as that pattern is about combining formerly unrelated types, not types which were primarily designed for being combined.
In other words, in practice, when you encounter multiple implementation classes that you wish to combine in one Adapter, you will still face multiple classes which you can’t combine via inheritance and the existence of the default method feature won’t change that.
So the bottom line is, before Java 8, this pattern could only be used with restrictions, and these restrictions still apply with Java 8. If you want to view these restriction as “It’s not possible”, then it is still not possible…

How to choose between abstract class and interface [duplicate]

This question already has answers here:
Interface vs Abstract Class (general OO)
(36 answers)
Closed 8 years ago.
I haven't done OOP in a while so I'm a bit rusty.
For an example, i have a client with a rental subscription, and it exist 3 type of subscription. How can i choose between abstract class and interface for my "Subscription" class?
Each subscription must have the price, maximum Rental Duration and maximum Rental Count.
From what I remember, I would use interface here but how can I force other classes that implements subscription to specify the value(constant) of these 3 properties?
If you're thinking of defining fields that are common to all implementations, you can't use an interface, because an interface does not contain state. It can just declare methods and constants. State is considered part of an implementation, not type information.
You could, however, define three abstract getter methods - getPrice(), getDuration() and getCount() or something like that, and leave the actual implementation of how those work to the implementing classes. In that case, you could use either an interface or an abstract class.
You'd choose an abstract class if you have some implementation that you want to have which is common to all subclasses. For example, if you have a specific way to perform "rent out", or "send reminder to renter" or other operations. Those methods will be concrete, and only the above three getters will be abstract.
If you don't have any common operations, and you find yourself just having the abstract methods and nothing else, an interface will probably serve you best, especially so because Java is single-inheritance, and using an interface will allow you to extend another class when you are creating your concrete classes.
These are just rules of thumb, though, not rules set in stone.
I think an abstract class makes more sense in this case. Use abstract classes when your classes all deal with the same data/methods but may slightly differ in method logic.
Interfaces may be more useful when you have several classes which have large differences but should always be constrained to a set of methods(the interface methods)
In general you use abstraction in case of inheritance and polymorphism. When you have an object that can have different behavior based on its internal type. Interfaces are used when there is a need for a contract. In general abstraction is best for objects that are closely related, while interfaces are chosen for their functionality.
In your case abstraction makes sense. You can keep the mutual properties in your base class and derive other classes from it. Eliminates some redundant code.
Here is what MS suggested:Here are some recommendations to help you to decide whether to use an interface or an abstract class to provide polymorphism for your components.
*If you anticipate creating multiple versions of your component, create an abstract class. Abstract classes provide a simple and easy way to version your components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, you must create a whole new interface.
*If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.
*If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.
*If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members.
https://msdn.microsoft.com/en-us/library/scsyfw1d(v=vs.71).aspx

Categories