The Decorator Pattern attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
Class Diagram
public abstract class Component {
public abstract void operate();
}
ConcreteComponent Role
public class ConcreteComponent extends Component {
@Override
public void operate() {
System.out.println("do Something");
}
}
Decorator Role
public abstract class Decorator extends Component {
private Component _component;
public Decorator(Component component) {
this._component = component;
}
@Override
public void operate() {
this._component.operate();
}
}
ConcreteDecorator Role
public class ConcreteDecorator1 extends Decorator {
public ConcreteDecorator1(Component component)
super(component);
}
private void method1() {
System.out.println("method1 Decorator");
}
public void operate() {
this.method1();
super.operate();
}
}
public class ConcreteDecorator2 extends Decorator {
public ConcreteDecorator2(Component component)
super(component);
}
private void method2() {
System.out.println("method2 Decorator");
}
public void operate() {
this.method2();
super.operate();
}
}
Client Role
public class Client {
public static void main(String[] args) {
Component component = new ConcreteComponent();
component = new ConcreteDecorator1(component);
component = new ConcreteDecorator2(component);
component.operate();
}
}
你也在研究Design Patterns啊~~
回覆刪除對阿,很久前就有在看了,不過沒什麼機會用到,久了就又忘了,Orz,所以就做些簡單的筆記,正妹也在學習喔,是興趣還是公司有在使用,XD。
回覆刪除