I am having an interface that holds three different methods. And there are two class Car and Plane which will implement the Vehicle interface to get access to those methods. There are two questions that I have in my mind.
1. What type of design pattern satisfies the following implementation?
2. Is there any other design pattern to satisfy similar kinds of functionalities?
Though I have tried some blogs and questions I have found one answer regarding the second question which is using Anonymous Class but which leads to more garbage code. So is there any solution or answer to my questions?
public interface Vehicle {
int set_num_of_wheels();
int set_num_of_passengers();
boolean has_gas();
}
public class Car implements Vehicle{
#Override
public int set_num_of_wheels() {
return 0;
}
#Override
public int set_num_of_passengers() {
return 0;
}
#Override
public boolean has_gas() {
return true;
}
}
public class Plane implements Vehicle{
#Override
public int set_num_of_wheels() {
return 0;
}
#Override
public int set_num_of_passengers() {
return 0;
}
#Override
public boolean has_gas() {
return true;
}
}
Polymorphism is just a fancy way to put different function pointers (chosen inconditionally by the concrete class) under a given function name.
So instead if you had a single class with a hashmap of methodenum-to-somefunctioninterface (method enum would just list the finite set of methods to hookup), then you could call the polymorphic functions by looking them up by the enum in the map, then casting to somefunctioninterface and calling it.
It entirely defeats the purpose of this OOP language, but that would be a distinct implementation.
It would fall into behavioral patterns for sure, but I guess it would be close to a Strategy or Plugin, given it's about delegating to classes incarnating the function.
BTW, that's pretty much what DynamicProxy is trying to do; proxy the interface without any impl class and delegate to a handler which figures a way to respon to the requested method.
Related
Disclaimer: I know there are a lot of questions about polymorphism out there, but I couldn't find a suitable answer for my problem. If your Google-fu is better than mine, please forgive the dupe.
I have a model using inheritance, such as in the example below.
public abstract class Base {
// ...
}
public class ConcreteA extends Base {
private String someString;
// ...
}
public class ConcreteB extends Base {
private boolean someBool;
// ...
}
And I also have a List<Base>, which is composed of objects that are either ConcreteAs or ConcreteBs.
I need to generate a graphical view for each object in the list, but the resulting element is not the same for ConcreteAs and ConcreteBs. From the example above, the view for ConcreteA would be a text field, while the view for a ConcreteB would be a check box.
How can I achieve this using OO principles?
The problem that you have is that you somewhere return a List<Base> when the caller must know the concrete type.
Usually this is caused because one tried to make a method more generic. E.g. if someone has this service methods
public List<ConcreteA> doSomethingA(){ ... }
public List<ConcreteB> doSomethingB(){ ... }
he might think it is a better idea to introduce a superclass, Base so that both methods can be substituted by
public List<Base> doSomething(){ ... }
This is a good idea if the caller is only interessted in a Base object. This means that ConcreateA and ConcreteB have some common behavior that the caller only depends on.
But in your case it seems that the caller needs the concrete type information that is not available anymore, because of the more generic method.
So you either must preserve or reconstruct the type information.
Preserve the type by using a custom return type instead of making the method generic
public class Result {
private List<ConcreteA> concreteA;
private List<ConcreteB> concreteA;
}
public Result doSomething();
Recunstruct the type information using instanceof
Reconstruct the type information by introcucing a visitor pattern.
Not a pattern - this is what abstraction is all about. Declare a method you want all subclasses of Base to implement and each must implement it in their own way.
Obviously you would pass parameters and/or get results of the methods.
public abstract class Base {
abstract void graphicalView();
}
public class ConcreteA extends Base {
#Override
void graphicalView() {
}
}
public class ConcreteB extends Base {
#Override
void graphicalView() {
}
}
public void test() throws IOException {
List<Base> bases = new ArrayList<>();
for ( Base b : bases ) {
b.graphicalView();
}
}
I think you're looking for Visitor Design Pattern.
From Wikipedia :
In object-oriented programming and software engineering, the visitor
design pattern is a way of separating an algorithm from an object
structure on which it operates. A practical result of this separation
is the ability to add new operations to extant object structures
without modifying the structures. It is one way to follow the
open/closed principle.
In essence, the visitor allows adding new virtual functions to a
family of classes, without modifying the classes. Instead, a visitor
class is created that implements all of the appropriate
specializations of the virtual function. The visitor takes the
instance reference as input, and implements the goal through double
dispatch.
In such cases, I usually use generics something like this
public abstract class Base <T extends Shape>{
public abstract T drawShape();
}
public class ConcreatA extends Base<Circle> {
#Override
public Circle drawShape() {
return null;
}
}
public class ConcreatB extends Base<Square> {
#Override
public Square drawShape() {
return null;
}
}
So now you can use list of Shapes
I am curious regarding java object copies and inheritance. Lets say I have the following two classes:
abstract class Algorithm {
public abstract void run();
}
class Specialized extends Algorithm {
#Override
public void run();
}
Now I want to test the specialized algorithm. And I really want to do this in parallel with multiple instances / parameters. The problem is that the run method is not reentrant, so I have to have per-thread instances of Specialized. Of course any kind AlgorithmRunner should work with the abstract class Algorithm to be able to test multiple different specializations. The problem is that I would need to construct a new ? extends Algorithm from an existing one in a generic fashion. How can I achieve this? I could easily write copy constructors for each kind of specialization but that would require switches using instanceof checks which I would rather avoid.
You could try using the Factory pattern:
interface AlgorithmFactory {
public abstract Algorithm createAlgorithm();
}
class SpecializedFactory implements AlgorithmFactory {
#Override
public Specialized createAlgorithm() {
return new Specialized();
}
}
Then passing an AlgorithmFactory to AlgorithmRunner allows it to instantiate the subclass of Algorithm without knowing its implementation.
There are a couple of ways to do this. One is to have Algorithm have an abstract factory method for getting instances:
abstract class Algorithm {
public abstract void run();
protected abstract Algorithm buildInstance();
}
class Specialized extends Algorithm {
#Override
public void run() {
// ...
}
#Override
protected Algorithm buildInstance() {
return new Specialized();
}
}
FWIW, I would lean toward having an AlgorithmRunner separate from Algorithm, and have it accept an instance of an AlgorithmCreator or similar with the factory method.
This question already has answers here:
Java - Method name collision in interface implementation
(7 answers)
Closed 8 years ago.
Shortly I came across an oddity, I can't explain to myself. The real-world problem is already worked around, I'm just curious if there is an satisfying answer I didn't find.
Imagine you have to write a class that implements the following interface from some framework you are using:
interface Interface1 {
String method();
}
So far so good. Now you introduce a second framework and it would be rather useful if your class would implement a second interface:
interface Interface2 {
Long method();
}
That's the point where the problem arises:
class ThatsTheProblem implements Interface1, Interface2 {
public ???? method() {
// ...
}
}
Any ideas?
Just for your information: The real-world problem is based on an abstract-dao-pattern where some entities had Long ids, others had UUID ids.
Short answer: you can't.
What you can do is provide a view that implements one or the other interface. For instance:
public class OnePossibleSolution { // no "implements"
private String interface1Method() {
return "whatever";
}
public Interface1 asInterface1() {
return new Interface1() {
#Override
String method() {
return interface1Method();
}
}
}
// ditto for Interface2...
This is probably the most Java-idiomatic way to solve the problem. It's what Map does when you want to iterate over its elements, for instance. Rather than try to solve the problem of being an Iterable<K>, Iterable<V> and Iterable<Map.Entry<K,V>>, it provides three views:
keySet()
values()
entrySet()
Each of those returns a respective collection, which implements the appropriate Iterable<...> interface.
Two of the components of a method declaration comprise the method signature—the method's name and the parameter types. These methods have the same signature, therefore cannot be implemented by one class.
Remember that in Java, you don't neccesary have to store the result of a method. If your ThatsTheProblem class compiled, and you had a class with this code, to which version of the method would invoke?
ThatsTheProblem ttp = new ThatsTheProblem();
ttp.method();
It is clearly impossible to create one object that implements two conflicting interfaces. However, it is possible for one object to provide two different facades, each implementing conflicting interfaces.
Note here that the two facades refer to common instance variables of the one object so they do, essentially, represent the same object.
public interface Interface1 {
String method();
}
public interface Interface2 {
Long method();
}
public class DiMorph {
String forInterface1 = "Number nine";
Long forInterface2 = 9L;
public Interface1 asInterface1() {
return new AsInterface1();
}
private class AsInterface1 implements Interface1 {
#Override
public String method() {
return forInterface1;
}
}
public Interface2 asInterface2() {
return new AsInterface2();
}
private class AsInterface2 implements Interface2 {
#Override
public Long method() {
return forInterface2;
}
}
}
public void testInterface1(Interface1 i1) {
}
public void testInterface2(Interface2 i2) {
}
public void test() {
DiMorph m = new DiMorph();
testInterface1 (m.asInterface1());
testInterface2 (m.asInterface2());
}
To quote #Andreas, this is simply impossible.
Imagine you have two workers, Alice and Bob, with two managers, Cathy and Dave. Cathy expects Alice to implement the Work() method and return a Java application. Dave, on the other hand, expects Bob to implement the Work() method and return a C++ library. What your question suggests is to introduce a new worker Eric who can do the Work() of Alice and Bob at the same time. What actually happens is that Eric is too overloaded to compile.
I have a question regarding the best design pattern for code reuse when dealing with Java enums. Basically, what I'm trying to achieve is being able to define several enums that model static business collections (sets of constants), but I'd also like to share behavior between them, with minimal coding.
This is trivial to achieve with class inheritance from abstract classes but, since Java enums cannot be extended (they can only implement interfaces), this type of work is tedious and involves a lot of error prone copy/paste work (copying the code from enum to enum). Examples of "business logic" that should be shared among all enums includes converting from/to Strings, instance and logical comparison, etc.
My best shot right now is using helper classes in conjunction with business interfaces, but this only goes so far in reducing code complexity (as all enums still have to declare and invoke the helper classes). See example (just to clarify):
public enum MyEnum {
A, B, C;
// Just about any method fits the description - equals() is a mere example
public boolean equals(MyEnum that) {
ObjectUtils.equals(this, that);
}
}
How do StackOverflowers deal with this "language feature"?
You can move the reusable logic to dedicated (non-enum) classes and then have the enums delegate to those classes. Here's an example:
[Side note: the inheritance of PlusTwo extends PlusOne is not recommended (b/c PlusTwo is not PlusOne). It here just to illustrate the point of being able to extend an existing logic.]
public interface Logic {
public int calc(int n);
}
public static class PlusOne implements Logic {
public int calc(int n) { return n + 1; }
}
public static class PlusTwo extends PlusOne {
#Override
public int calc(int n) { return super.calc(n) + 1; }
}
public static enum X {
X1, X2;
public Logic logic;
public int doSomething() {
return logic.calc(10);
}
}
public static enum Y {
Y1, Y2;
public Logic logic;
public String doSomethingElse() {
return "Your result is '" + logic.calc(10) + "'";
}
}
public static void main(String[] args) {
// One time setup of your logic:
X.X1.logic = new PlusOne();
X.X2.logic = new PlusTwo();
Y.Y1.logic = new PlusOne();
Y.Y2.logic = new PlusTwo();
System.out.println(X.X1.doSomething());
System.out.println(X.X2.doSomething());
System.out.println(Y.Y1.doSomethingElse());
System.out.println(Y.Y2.doSomethingElse());
}
I would do the same, or combine the Enums into a super-enum.
With Java 8 this will be easier. You will be able to define a default implementation for interface methods and have the enum extend the interface.
I rarely find enums useful, except for representing finite states in which case they do not need behavior.
I would suggest refactoring enums that need behavior into classes with a Factory.
This might look a bit ugly, but generally can offer you the required functionality.
You can have interface
public interface MyEnumInterface<T extends Enum<T>> {
String getBusinessName();
T getEnum();
}
Implementation
public enum OneOfMyEnums implements MyEnumInterface<OneOfMyEnums>{
X, Y, Z;
#Override
public String getBusinessName() {
return "[OneOfMyEnums]" + name();
}
#Override
public OneOfMyEnums getEnum() {
return this;
}
}
And utility class instead of your parent class
public class MyEnumUtils {
public static <T extends Enum<T>> String doSomething(MyEnumInterface<T> e){
e.getBusinessName(); // can use MyEnumInterface methods
e.getEnum().name(); // can use Enum methods as well
return null;
}
}
What would be the practical side of the ability to define a class within an interface in Java:
interface IFoo
{
class Bar
{
void foobar ()
{
System.out.println("foobaring...");
}
}
}
I can think of another usage than those linked by Eric P: defining a default/no-op implementation of the interface.
./alex
interface IEmployee
{
void workHard ();
void procrastinate ();
class DefaultEmployee implements IEmployee
{
void workHard () { procrastinate(); };
void procrastinate () {};
}
}
Yet another sample — implementation of Null Object Pattern:
interface IFoo
{
void doFoo();
IFoo NULL_FOO = new NullFoo();
final class NullFoo implements IFoo
{
public void doFoo () {};
private NullFoo () {};
}
}
...
IFoo foo = IFoo.NULL_FOO;
...
bar.addFooListener (foo);
...
I think this page explains one example pretty well. You would use it to tightly bind a certain type to an interface.
Shamelessly ripped off from the above link:
interface employee{
class Role{
public String rolename;
public int roleId;
}
Role getRole();
// other methods
}
In the above interface you are binding the Role type strongly to the employee interface(employee.Role).
One use (for better or worse) would be as a workaround for the fact that Java doesn't support static methods in interfaces.
interface Foo {
int[] getData();
class _ {
static int sum(Foo foo) {
int sum = 0;
for(int i: foo.getData()) {
sum += i;
}
return sum;
}
}
}
Then you'd call it with:
int sum = Foo._.sum(myFoo);
I can say without hesitation that I've never done that. I can't think of a reason why you would either. Classes nested within classes? Sure, lots of reasons to do that. In those cases I tend to consider those inner classes to be an implementation detail. Obviously an interface has no implementation details.
One place this idiom is used heavily is in XMLBeans. The purpose of that project is to take an XML Schema and generate a set of Java classes that you can use bidirectionally to work with XML documents corresponding to the schema. So, it lets you parse XML into xml beans or create the xml beans and output to xml.
In general, most of the xml schema types are mapped to a Java interface. That interface has within it a Factory that is used to generate instances of that interface in the default implementation:
public interface Foo extends XmlObject {
public boolean getBar();
public boolean isSetBar();
public void setBar(boolean bar);
public static final SchemaType type = ...
public static final class Factory {
public static Foo newInstance() {
return (Foo)XmlBeans.getContextTypeLoader().newInstance(Foo.type, null);
}
// other factory and parsing methods
}
}
When I first encountered this it seemed wrong to bind all this implementation gunk into the interface definition. However, I actually grew to like it as it let everything get defined in terms of interfaces but have a uniform way to get instances of the interface (as opposed to having another external factory / builder class).
I picked it up for classes where this made sense (particularly those where I had a great deal of control over the interface/impls) and found it to be fairly clean.
I guess you could define a class that is used as the return type or parameter type for methods within the interface. Doesn't seem particularly useful. You might as well just define the class separately. The only possible advantage is that it declares the class as "belonging" to the interface in some sense.
Google Web Toolkit uses such classes to bind 'normal' interface to asynchronous call interface:
public interface LoginService extends RemoteService {
/**
* Utility/Convenience class.
* Use LoginService.App.getInstance() to access static instance of LoginServiceAsync
*/
class App {
public static synchronized LoginServiceAsync getInstance() {
...
}
}
}
With a static class inside an interface you have the possibility to shorten a common programming fragment: Checking if an object is an instance of an interface, and if so calling a method of this interface. Look at this example:
public interface Printable {
void print();
public static class Caller {
public static void print(Object mightBePrintable) {
if (mightBePrintable instanceof Printable) {
((Printable) mightBePrintable).print();
}
}
}
}
Now instead of doing this:
void genericPrintMethod(Object obj) {
if (obj instanceof Printable) {
((Printable) obj).print();
}
}
You can write:
void genericPrintMethod(Object obj) {
Printable.Caller.print(obj);
}
Doing this seems to have "Bad design decision" written all over it.
I would urge caution whenever it seems like a good idea to create a non-private nested class. You are almost certainly better off going straight for an outer class. But if you are going to create a public nested class, it doesn't seem any more strange to put it in an interface than a class. The abstractness of the outer class is not necessarily related to the abstractness of a nested class.
This approach can be used to define many classes in the same file. This has worked well for me in the past where I have many simple implementations of an interface. However, if I were to do this again, I would use an enum which implements an interface which would have been a more elegant solution.