What is decorator design pattern in Java?
1. Decorator design pattern is used to enhance the functionality of a particular object at run-time or dynamically.
2. At the same time other instance of same class will not be affected by this so individual object gets the new behavior.
3. Basically we wrap the original object through decorator object.
4. Decorator design pattern is based on abstract classes and we derive concrete implementation from that classes
5. It’s a structural design pattern and most widely used.
Problem Solved in Decorator:
If anyone wants to add some functionality to indidual objects or change state of particular object at run time. it is not possible what the possible is we can provide the specific behavior to all the object of that class at design time by the help of inheritance or using subclass, but Decorator pattern makes possible that we provide individual object of same class a specific behavior or state at run time.
When use Decorator:
when sub classing becomes impractical and we need large number of different possibilites to make independent objects. (we have number of combinations in object)
add functionality at run time to individual object.
Example :
interface car{ //1. Component interface / abstract classes
void assemble();
}
class BasicCar implements car { //2. Component implementation 1
public void assemble(){
System.out.println("basis Car");
}
}
class HondaCar implements car { //2. Component implementation 2
public void assemble(){
System.out.println("honda Car");
}
}
//3. Decorator: Implements Components interface and it has a
// relationship with the component interface.
class CarDecorator implements car{
car car;
public CarDecorator(car c) {
// TODO Auto-generated constructor stub
this.car = c;
}
public void assemble() { this.car.assemble(); }
}
//4. Concrete Decorators 1
class sportsCar extends CarDecorator{
public sportsCar(car c) {
// TODO Auto-generated constructor stub
super(c);
}
public void assemble(){
car.assemble();
System.out.println("adding featurs of SportsCar");
}
}
//4. Concrete Decorators 2
class LexCar extends CarDecorator{
public LexCar(car c) {
// TODO Auto-generated constructor stub
super(c);
}
public void assemble(){
car.assemble();
System.out.println("adding featurs of LexCar");
}
}
public class test {
public static void main(String[] args) {
car c = new sportsCar(new BasicCar());
car c1 = new sportsCar(new LexCar(new HondaCar()));
c.assemble();
c1.assemble();
}
}
Decorator Patterns is widely used in Java.IO package such as BufferedReader, FileReader etc .
Pros:
1. Pattern is flexible then inheritance because inheritance adds responsibility at compile time.
2. Enhance and modify object functionality.
Cons:
Code modifications can be a problem as it uses smaller kind of objects.
No comments:
Post a Comment