Core Java Design Pattern : Structural Pattern : Decorator Design Pattern
Decorator Design Pattern |
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
Also Known As : Wrapper
Use Decorator pattern when
- to add responsibilities to individual objects dynamically and transparently, that is, without affecting other objects.
- for responsibilities that can be withdrawn.
- when extension by subclassing is impractical. Sometimes a large number of independent extensions are possible and would produce an explosion of subclasses to support every combination.
For example, suppose we have a TextView object that displays text in a window. TextView has no scroll bars by default, because we might not always need them. When we do, we can use a ScrollDecorator to add them. Suppose we also want to add a thick black border around the TextView. We can use a BorderDecorator to add this as well. We simply compose the decorators with the TextView to produce the desired result.
Examples |
Window.java
package com.javaskool;
class Window {
public void draw() {
// Draw window
System.out.println("Windows Drawn");
}
public void setSize(int height, int width) {
// Set window size
System.out.println("With Size "+ height+ " , "+width);
}
// Other Window methods
}
HorizontalScroller.java
package com.javaskool;
class HorizontalScroller extends Window {
private Window myWindow;
public HorizontalScroller (Window baseWindow){
myWindow = baseWindow; // Save the reference, which we will use
System.out.println("Window with Horizontal Scrollbar..");
}
public void draw() {
//draw the horizontal scroller
myWindow.draw();
}
public void setSize(int height, int width) {
//implement horizontal scroller-specific functionality
myWindow.setSize(height, width);
}
}
VerticalScroller.java
package com.javaskool;
class VerticalScroller extends Window {
private Window myWindow;
public VerticalScroller (Window baseWindow){
myWindow = baseWindow; // Save the reference, which we will use
System.out.println("Window with Vertical Scrollbar..");
}
public void draw() {
//draw the vertical scroller
myWindow.draw();
}
public void setSize(int height, int width) {
//implement vertical scroller-specific functionality
myWindow.setSize(height, width);
}
}
TestDrive.java
package com.javaskool;
public class TestDrive {
public static void main(String[] args) {
Window theWindow=new Window();
theWindow.draw();
theWindow.setSize(300, 200);
//theWindow = new VerticalScroller (theWindow);
theWindow = new HorizontalScroller(theWindow);
}
}
Output
c:\>javac -d . *.java
c:\>java com.javaskool.TestDrive
Windows Drawn
With Size 300 , 200
Window with Horizontal Scrollbar..
Recent Comments