结构型模式:结构型对象模式不是对接口或实现进行组合的.而是描述了如何对一些对象进行组合,从而实现新功能的一些方法.
decorator:动态的给一个对象添加一些额外的职责.
package structure.decorator;
/**
* The top abstract where concrete component and decorator
* should be derived from
*/
public interface Component {
public abstract void PrintString(String s);
}
package structure.decorator;
/**
* A Concrete Component
*/
import java.io.*;
public class ConcreteComponent implements Component {
public ConcreteComponent() {
}
public void PrintString(String s) {
System.out.println("Input String is:" + s);
}
}
package structure.decorator;
/**
* The Concrete Decorator
*/
import java.io.*;
public class ConcreteDecoratorA extends Decorator {
public ConcreteDecoratorA(Component c) {
super(c);
}
public void PrintString(String s) {
super.PrintString(s);
PrintStringLen(s);
}
public void PrintStringLen(String s) {
System.out.println("The length of string is:" + s.length());
}
}
package structure.decorator;
/**
* The Decorator
*/
public class Decorator implements Component {
private Component component;
public Decorator(Component c) {
component = c;
}
public void PrintString(String s) {
component.PrintString(s);
}
}
package structure.decorator;
/**
* A simple test
*/
public class Test1 {
public static void main(String[] args) {
Component myComponent = new ConcreteComponent();
myComponent.PrintString("A test String");
Decorator myDecorator = new ConcreteDecoratorA(myComponent);
myDecorator.PrintString("A test String");
}
}