Consider that we have a Car object. The acceleration and breaking features are implemented using strategy pattern. But what if we want to introduce nitro gas feature to an existing car object ? What is the design pattern that I can use ?
I want to add the nitro feature(Attribute) after creating the car object.
You can check the Decorator pattern, it can be used to dynamically add functionality to an existing object.
Decorator pattern can add different functionalities to objects dynamically. But these functionalities have to be implemented in a Concrete Decorator. The developer can decide what functionalities to add at run time.
In statically typed languages you can not add methods to an object at runtime. Compiler, when it encounters a statement like: car.nitroAccelerate(), checks whether a car object implements any interface that has nitroAccelerate method. If you could add (or remove) methods during runtime such checks would be impossible.
Dynamic languages allow to add methods during runtime. But this has a drawback, when you put car.nitroAccelerate() in the code, you need to carefully analyze if the car object in this point has such method.
You can use decorator to modify existing methods at runtime, but doing so, you are not modifying an existing object, just creating a new one that wraps the old one.
So if you do something like:
Car fasterCar = new CarWithNitro(car);
and some piece of your code still holds a reference to the original car, this original car would not be faster, because the act of wrapping does not modify the original.
If you want to add new methods, you need to create a new subclass and/or use delegation. This will be necessary if the "nitro" feature requires an explicit method call to activate.
If however all you want to do is to add to existing functionality without adding methods, Decorator is a good bet. Let's say that interface "Car" has a method called floorIt(). In that case, you can add a "nitro kick" to floorIt with Decorator without having to add to the Car inteface.
Of course, there's a middle ground. If you use runtime type discovery and/or multiple interfaces, you can both use Decorator and add methods to the resulting object.
I'll show you two methods of creating it; one is neither good nor bad and the other one is better.
Method 1
You can use Generic and Interface for that new Feature. The advantage is that you don't need to wrap inside the new object for a new field or attribute.
Create a Feature interface.
public interface Feature<T> {
T getClassValue();
void setClassValue(T feature);
}
Add it to the concrete class.
public class Car<ReturnType> {
//acceleration and breaking features are added using the strategy pattern
public Feature<ReturnType> newFeature;
public Car(Feature<ReturnType> features) {
this.newFeature = features;
}
public Feature<ReturnType> getNewFeature() {
return newFeature;
}
public void setNewFeature(Feature<ReturnType> newFeature) {
this.newFeature = newFeature;
}
}
Problem: The problem is that the new feature can be NULL. It also breaks the Single Responsibility Principle because the car has the responsibility to add the feature. It would populate more Generics to some Abstract classes later on.
Car<Void> car1 = new Car<>(null);
car1.getNewFeature(); //catch Exception here!
And you also have to catch NullPointerException for that. Even thinking with Visitor Design Pattern, its accept(Visitor v); method is always there even if there's no visitor yet.
Advantage: So, is there anything good about it? Yes, there is!
Now, we're gonna create an AbstractFeature class first.
public abstract class AbstractFeature<T> implements Feature<T> {
protected T concreteClass;
#Override
public T getConcreteClass() {
return concreteClass;
}
#Override
public void setConcreteClass(T concreteClass) {
this.concreteClass = concreteClass;
}
}
Now, we're gonna create what kind of new Feature Class we want. Let's say, we wanna add NitrogenGas to the car. Let's create it first. Note: It's a free class. You can add fields as many as you want here. And we'll call this class and use it later.
public class NitrogenGas {
//some methods
public String fillGas() {
return "Filling NitrogenGas";
}
}
And let's add a feature later like this! Just use the AbstractFeature class. That's the reusability.
public class NitrogenGasFeature extends AbstractFeature<NitrogenGas> {
}
Now, you can add a new Feature to the Car class like this! The NitrogenFeature class holds a concrete class we want to use.
Car<NitrogenGas> car2 = new Car<>(new NitrogenGasFeature()); //Feature added
car2.getNewFeature().setConcreteClass(new NitrogenGas()); //Concrete Class added
car2.getNewFeature().getConcreteClass().fillGas(); //use its method.
Let's try and use a Wrapper class like Boolean. Just in case you just need it for backtracking or something.
Car<Boolean> car2 = new Car<>(new BooleanFeature());
car2.getNewFeature().ConcreteClass(new Boolean(true));
System.out.println(car2.getNewFeature().getConcreteClass().booleanValue());
FYI, we can create BacktrackingFeature and Backtracking classes for readability. But it will increase more code. So, use think it wisely.
This is method 1. It breaks the Single Responsibility, more dependency and more code but increases reusability and readability. Sometimes, when you think too much on the code, even inheritance breaks the Single Responsibility. And that's why we use Composition with the interface. Rules are meant to be broken for the great good.
Method 2 The DTO pattern. You can use like the above answer. Just create a new Object and wrap it. Add any fields or attributes you want to use it. That's the better way. It doesn't break the Single Responsibility Principle. And it has a more meaningful OOP way. But it's up to your decision to make.
Related
I am studying Design Patters and I have a situation where I am not sure what would be a better practice:
I have a class "Category" which has several fields: name, 2 kinds of urls, list of related objects. There is a method 'toHtml()' which basically generates some HTML from instances of that class.
There are 4 different types of 'Categories' which have exactly the same fields but 'toHtml()' method should give different result for each one.
I am not sure if I should pass a parameter "type" and series of ifs/switch statement to generate different html or should I make a Category class abstract and create several sub-classes that override the toHtml() method and then use CategoryFactory class to generate them? In both cases I need to pass 'type' parameter.
I tried to think about 'Close for modification, open for extension' OOP rule. But in this case if I want to add 'fifth' category type, that generates different html - for first solution I need to modify only toHtml method (adding one more if), going for second solution I need to create additional sub-class AND modify CategoryFactory class.
What would be better practice? Is there any extra rule I should follow when I have similar kind of dilemma?
First, I believe you are referring to the Factory Method, and not the Abstract Factory Pattern.
The main difference being, in the former you define a common template for a single product, whereas in the latter you define a template for a family of products. For more information, you could look here.
In your case, you wish to define a template for Category. With this assumption, here is what your group of classes would look like:
abstract class Category {
public void doSomething() {
Foo f = makeFoo();
f.whatever();
}
abstract void toHtml();
}
class Category1 extends Category {
public override void toHtml() {
... // do something here
}
}
class Category2 extends Category {
public override void toHtml() {
... // do something else here
}
}
It is true that this certainly a lot of code, and could easily be represented like this:
class Category {
public void toHtml(Integer param) {
if(param == 1) { // do something for Category1
}
else { // do something for Category2
}
}
At the end of the day, it really is a design decision. There are some factors you can consider. Is this going to be a constantly changing class? Is this going to be declared global for the customer to use? How do you want the customer to be able to use this?
The easier thing at this point would be to take the path of least resistance. Having one class to service all categories certainly results in lesser code and in Salesforce, less code is always a better thing. But consider this: Abstracting your functionality into separate classes makes for more maintainable code. You may find it easier to write a class and a wall of if statements, but tomorrow when you're not around and there's a critical failure and someone has to look through your code to figure out exactly which if caused the problem, they'll curse you for it.
Keep in mind that inheritance is an all or nothing mechanism. You may find it particularly useful to use if you have some common functionality, in which case you can choose to abstract that out into the parent class and have your children take care of the specifics.
If you create a subclass of Category and override the toHtml () method, why do you need to have a factory pattern. The toHtml () method of the runtime resolved class will be called if you are calling it using the reference. This implies that if you add a new Category subclass then you override the toHtml () method and it should work fine.
I am learning java concepts.
I got a doubt in java inheritance concept.
In inheritance we can assign subclass instance to a base class reference
and with that we can access only base class function.
and we can assign any subclass instance in the hierarchy of inheritance to base class reference.For an type of instance assigning to a particular base class reference we can access only base class functions and i didn't find any difference.
Can any one give me actual concept
why we have to assign subclass instances to base class references?
what is the need to do that?
Instead we can access those base class functions from subclass reference only know.
Explain by considering a particular base class and many subclasses in the hierarchy.
The reason why you may want to do this is to create more robust designs. Take for example the Collections Framework in Java. You have a List interface and then you have two implementations, ArrayList and LinkedList.
You can write your program to use a LinkedList specifically or an ArrayList specifically. However, your program then depends on those specific implementations.
If you write your program to depend on the super type, List, instead then your program can work for either of the List implementations. Lets say you want to write a method that does something to a List and you wrote this:
public void doSomething(ArrayList a){}
This method can only be called with an ArrayList, not a LinkedList. Suppose that you wanted to do the same thing with a LinkedList? Do you then duplicate your code? No.
public void doSomething(List l){}
Will be able to accept either type of List.
The principle behind this is program to an interface not an implementation. That is, List defines the functions of ALL lists.
There are many many examples of this usage.
Inheritance and Polymorphism are cornerstones of object-oriented programming and serve a few different purposes, in short:
Code reuse by extending a base class with specific functionality,
Interface design by providing an abstract set of functionality, which where different implementations are tailored to different requirements and
Encapsulation by hiding specific functionality, which isn't needed in certain contexts
among others.
The last point also highlights, why one might use a restricted set of functionality, even in a case the actual implementation provides more than that. Take for example the Collection interface. By using this interface, we focus on methods like isEmpty, contains or size but not the actual implementation.
What you've described is the essence of polymorphism. It's a word from the Greek that means "many forms".
If I gave you a simple hierarchy like this, you can see how the test code can get different calculation implementations out of each object without concerning itself about what kind of Shape it was dealing with:
public interface Shape
{
double calculateArea();
}
class Circle implements Shape
{
private double radius;
Circle(double r) { this.radius = r; }
public double calculateArea() { return Math.PI*radius*radius; }
}
class Square implements Shape
{
private double side;
Square(double s) { this.side = s; }
public double calculateArea() { return side*side; }
}
// This would be a separate JUnit or TestNG annotated test.
public class ShapeTest
{
#Test
public void testCalculateArea()
{
Map<Shape, Double> expected = new HashMap<Shape, Double>()
{{
put(new Circle(1.0), Math.PI);
put(new Square(1.0), 1.0);
}};
for (Shape shape : expected.keySet())
{
Assert.assertEquals(expected.get(shape), shape.calculateArea());
}
}
}
Polymorphism.
I am a method that gives you a List<String>. All you need to know about the thing I've actually given you is that it's a list and has the behaviour and semantics of a list, i.e. you can put things in it, it'll maintain their ordering, and you can iterate over it.
What you don't need to know is how I'm storing things, how I'm making them accessible, etc. That's not important. For all you care, it could be a LinkedList<String>, an ArrayList<String> or something entirely new. Suffice it to say, I've picked something, and you can happily use it.
You're absolutely right that when you're using inheritance to extend classes and add new behaviour, then you need to reference the subclass to be able to access it. The two approaches are somewhat complimentary, but different, use cases.
Let us say Vehicle is the base class and Car and Plane are subclasses. Let us say Vehicle has has a method move().
Car overrides this by going on road. Plane overrides this by flying.
Why move() should be part of Vehicle base class?
Because any Vehicle can move(). But we can't implement move() in Vehicle because all vehicles doesn't move the same way i.e. there is no common behavior. We still want this in the base class so that we can have polymorphic behavior i.e. we can write code like below. As you can see there is only one method called runVehicle(...) that can work on any Vehicle class.
void runVehicle(Vehicle v)
{
v.move();
}
Car c=new Car();
runVehicle(c);
Plane p=new Plane();
runPlane(p);
There is no real need to do that, except when the API demands it. For example, if in a particular API or code library there is a
void ReallyUsefulFunction(BaseClass instance)
that you would like to use, you can derive a class fom BaseClass and implement its methods in the SubClass. Then you can now pass the subclass to the function.
Still, technically, you could implement your own
void MyReallyUsefulFunction(MyClass instance)
which imitates the same functionality. But like what MYYM had explained, the benefits of code reuse etc. can be huge, and that is when you will want to take advantage of polymorphism.
First of all this is not a question about how to implement an interface in Java, or about an error with interfaces. This is a question about the right way to do it, depending on the situation.
First of all i would like to apologize if this is not the correct "stack" to post this question, please let me know and i'll move it to another one.
Let's begin.
What i'm trying to guess is which is the best way to implement an interface in Java. Let's say we have a class A like:
public Class A {
public A(){}
public void fooA() {}
}
And an interface
public interface MyListener {
public void fooListener();
}
Inside fooA() I'm making use of interface B this way:
...
something.setFooListener(/**Doubts here**/)
....
What should we type inside setFooListener(...)
Options are (As far as i know):
A) Define the behavior inside the setFooListener function:
new MyListener.fooListener() {
/** Implementation of fooListener() **/
}
Pros:
Easy and readable as you're reading the function.
You can access directly to FINAL variables defined in fooA().
Cons:
If your implementation is long enough it would end up in a lack of readability and a too long function.
If you're implementing the interface in a few places on the same class you are going to repeat a lot of code.
B) Create an inner class implementing the interface:
private class MyListenerImplementation implements MyListener {
private String var1;
private int var2;
public MyListenerImplementation() {/** constructor **/}
public void fooListener() {
/** Do logic here **/
}
}
Pros:
You can keep a reference to the object MyListenerImplementation.
You can define variables, functions and everything as it's an object like any other one.
Cleaner code.
Cons:
Maybe needs more memory.
Maybe creating unnecessary classes
C) Hold a variable with a reference to the interface implementation
private MyListener.FooListener myListenerVar = new MyListener.FooListener() {
/** Logic goes here **/
};
Pros:
I actually can't sees anyone comparing to B, but a lot of cons.
Cons:
Not a clean code. Doing this on top of your class would be, at least, a war crime.
I don't think it's correct to assign a block of code to a variable.
I don't like how this looks ;)
D) The last one i could think of; define a function and inside return the implementation
private MyListener.fooListener createMyListener() {
return new MyListener.fooListener() {
/** Logic goes here **/
}
}
Pros:
It's cleaner than C.
Reusability
Cons:
Almost the same ones as C.
I don't think it's correct to return a whole block of code.
To sum up: Which i like the most is "B", but i would like to know what does SO thinks of this.
Thanks in advice.
Option A is not syntaxically correct. Your pros and cons are valid.
Option B:
Maybe needs more memory: no.
Maybe creating unnecessary classes: no. Option A also creates a class. It's anonymous, but it's a class, that must be loaded by the ClassLoader like any other class.
Option C: it's exactly the same as A (anonymous class usage), except you initialize a field with the listener. The rule is the same as for any other variable: reduce its scope as much as possible. If you need a field scope, use this option. If you only need the listener in one method, then use a local variable (option A).
Option D: once again, it's the same as A, except you return the created listener instead of only using it.
My recap: you're mixing three orthogonal problems here.
Should I use an anonymous inner class, a named nested class, or a top-level class. This depends on the amount of code contained in the class, and on where you need to use this class: in a single top-level class, or in many top-level classes.
Should I use local variables or instance variables. it's a matter of scope and state, not a matter of interface implementations. Your field or local variable can be initialized with an instance of any kind of your interface implementation
Should you use a factory method returning instances, or should you use new directly. Once again, that has nothing to do with how your interface is implemented. If you want to be loosely coupled, because the factory method might return different implementations of the same interface, use a factory. Otherwise, new is fine.
I'm designing of a project I have to do. For that, I have thought to use decorator design pattern. However, I have to adjust my design to the existing implementation of the project. Then, I can't keep completely the decorator design pattern.
The project has an abstract base class (called A) and a set of sub-class (called A1, A2, A3, A4, etc.). I can't modify the code of these classes.
Then, I have to add extra funcionality to these classes. For that, I create an abstract class (called B) that use to class A (Decorator). I also create concrete decorators that use to classes A1,A2,A3,A4,...
NOTE: As you see, I don't use any interface because the class A doesn't use any interface and I can't modify this code.
But I see some issues in this design:
1) Classes B1,B2,B3,B4,... have to add all methods of classes A1,A2,A3,A4,... for calling to methods of classes A1,A2,A3,A4... For example, in class B1:
class B1 {
public A1 objectA1;
B1() {
objectA1 = new A1();
}
public void add(int value) {
objectA1.add(value);
// extra funcionality
}
}
It can be a problem because if other developers modify the code of classes A,A1,A2,A3,A4,... they also need to modify the code of B,B1,B2,B3,B4,...
I WANT TO PREVENT THAT.
2) Moreover, classes A,A1,A2,A3,A4 have protected methods that only can be accessed from the own class or sub-classes. As I need to access to these methods, I can't use the decorator design pattern.
SECOND ALTERNATIVE
I could extend the classes A1,A2,A3,A4 with B1,B2,B3,B4. For example:
class B1 extends A1 {
B1() {
objectA1 = new A1();
}
public void add(int value) {
super.add(value);
// extra funcionality
}
}
Of this way, I solve the second problem and avoid to override all methods of A1, overriding only necessary methods. Even so, each time a sub-class of A is created, it's necessary to create the corresponding class B.
I WANT TO PREVENT THAT because it only is necessary that class B (B1,B2,...) override a method of class A (A1,A2,...).
THIRD ALTERNATIVE
Then, I thought that I could consider to class B (B1,B2,...) as a wrapper of class A (A1,A2,...). Of this way, a instance of B will be created as next:
new BMaker.get(A1, params_of_constructor_A1)
new BMaker.get(A2, params_of_constructor_A2)
new BMaker.get(A3, params_of_constructor_A3)
new BMaker.get(A4, params_of_constructor_A4) or
...
new BMaker.get(AN, params_of_constructor_AN)
where BMaker.get is a static method.
public static <T extends A> A get (T objectA, params ) {
// return anonymous class (*1)
}
My question is if it's possible to implement an anonymous class that inherit of A1, A2, ...
Each call to BMaker.get() should be created a different anonymous class deppending on if the first parameter of BMaker.get() is A1,A2,A3,...
Really, I don't know if it's possible to do this or is there another better way.
Any help would be appreciated!
Answer to the first issue:
Either put an interface I on A so your decorators/delegates can implement same interface, or
Create an interface I (equivalent to A's api) and a wrapper class AW which wraps A and implements I by passing all calls straight onto it.
Convert your client code to use I rather than A, and you can then happily proceed to build decorators/ or delegates using the new interface having "wrapped up" the old crunk in AW.
The one notable issue that arises is that some styles of code using A (IdentityHashMaps, persistence) may want a reference to the "underlying" A. If that comes up, you can put a method in the interface getUnderlyingA(). Try and avoid using that too much, since it obviously bypasses all decoration.
Second issue: decorating subtypes.
The question here is whether the subtypes need to be exposed as different decorator types -- or whether one uniform decorator can be exposed, that (maybe, if necessary) is internally aware of the type-system of the A subtypes that it can wrap.
If the subtypes are well-known & stable, you can implement a "handle style" api in the interface. For example, for file-system entities, you would present a handle of a single type but offer isFile(), isDirectory(), isDevice(), isDrive(), isRaw() etc methods for interrogating the type. A listFiles() method could be available to use the directory subtype.
My question is why you need external access (from the decorator) to protected methods? If you do, those methods should be public and the original design is broken/insufficiently extensible.
Maybe you can create a static helper class in the same package (if not changing the A class itself) that will give you proper access to this legacy crunk from your decorator.
There's a certain point here, where doing your job properly does sometimes involve working with & potentially upgrading legacy code. If there isn't an efficient & maintainable design alternative, that shouldn't be a total sticking point. Doubling up the type-system (creating two parallel heirarchies) is definitely not what you should be doing.
If there isn't a good way to do this, you should work on something else (a different feature/requirement) rather than making the codebase even worse.
I am learning java concepts.
I got a doubt in java inheritance concept.
In inheritance we can assign subclass instance to a base class reference
and with that we can access only base class function.
and we can assign any subclass instance in the hierarchy of inheritance to base class reference.For an type of instance assigning to a particular base class reference we can access only base class functions and i didn't find any difference.
Can any one give me actual concept
why we have to assign subclass instances to base class references?
what is the need to do that?
Instead we can access those base class functions from subclass reference only know.
Explain by considering a particular base class and many subclasses in the hierarchy.
The reason why you may want to do this is to create more robust designs. Take for example the Collections Framework in Java. You have a List interface and then you have two implementations, ArrayList and LinkedList.
You can write your program to use a LinkedList specifically or an ArrayList specifically. However, your program then depends on those specific implementations.
If you write your program to depend on the super type, List, instead then your program can work for either of the List implementations. Lets say you want to write a method that does something to a List and you wrote this:
public void doSomething(ArrayList a){}
This method can only be called with an ArrayList, not a LinkedList. Suppose that you wanted to do the same thing with a LinkedList? Do you then duplicate your code? No.
public void doSomething(List l){}
Will be able to accept either type of List.
The principle behind this is program to an interface not an implementation. That is, List defines the functions of ALL lists.
There are many many examples of this usage.
Inheritance and Polymorphism are cornerstones of object-oriented programming and serve a few different purposes, in short:
Code reuse by extending a base class with specific functionality,
Interface design by providing an abstract set of functionality, which where different implementations are tailored to different requirements and
Encapsulation by hiding specific functionality, which isn't needed in certain contexts
among others.
The last point also highlights, why one might use a restricted set of functionality, even in a case the actual implementation provides more than that. Take for example the Collection interface. By using this interface, we focus on methods like isEmpty, contains or size but not the actual implementation.
What you've described is the essence of polymorphism. It's a word from the Greek that means "many forms".
If I gave you a simple hierarchy like this, you can see how the test code can get different calculation implementations out of each object without concerning itself about what kind of Shape it was dealing with:
public interface Shape
{
double calculateArea();
}
class Circle implements Shape
{
private double radius;
Circle(double r) { this.radius = r; }
public double calculateArea() { return Math.PI*radius*radius; }
}
class Square implements Shape
{
private double side;
Square(double s) { this.side = s; }
public double calculateArea() { return side*side; }
}
// This would be a separate JUnit or TestNG annotated test.
public class ShapeTest
{
#Test
public void testCalculateArea()
{
Map<Shape, Double> expected = new HashMap<Shape, Double>()
{{
put(new Circle(1.0), Math.PI);
put(new Square(1.0), 1.0);
}};
for (Shape shape : expected.keySet())
{
Assert.assertEquals(expected.get(shape), shape.calculateArea());
}
}
}
Polymorphism.
I am a method that gives you a List<String>. All you need to know about the thing I've actually given you is that it's a list and has the behaviour and semantics of a list, i.e. you can put things in it, it'll maintain their ordering, and you can iterate over it.
What you don't need to know is how I'm storing things, how I'm making them accessible, etc. That's not important. For all you care, it could be a LinkedList<String>, an ArrayList<String> or something entirely new. Suffice it to say, I've picked something, and you can happily use it.
You're absolutely right that when you're using inheritance to extend classes and add new behaviour, then you need to reference the subclass to be able to access it. The two approaches are somewhat complimentary, but different, use cases.
Let us say Vehicle is the base class and Car and Plane are subclasses. Let us say Vehicle has has a method move().
Car overrides this by going on road. Plane overrides this by flying.
Why move() should be part of Vehicle base class?
Because any Vehicle can move(). But we can't implement move() in Vehicle because all vehicles doesn't move the same way i.e. there is no common behavior. We still want this in the base class so that we can have polymorphic behavior i.e. we can write code like below. As you can see there is only one method called runVehicle(...) that can work on any Vehicle class.
void runVehicle(Vehicle v)
{
v.move();
}
Car c=new Car();
runVehicle(c);
Plane p=new Plane();
runPlane(p);
There is no real need to do that, except when the API demands it. For example, if in a particular API or code library there is a
void ReallyUsefulFunction(BaseClass instance)
that you would like to use, you can derive a class fom BaseClass and implement its methods in the SubClass. Then you can now pass the subclass to the function.
Still, technically, you could implement your own
void MyReallyUsefulFunction(MyClass instance)
which imitates the same functionality. But like what MYYM had explained, the benefits of code reuse etc. can be huge, and that is when you will want to take advantage of polymorphism.