public class DecoratorA implements MyInterface{
MyInterface myObject;
public DecoratorA(MyInterface myObject) {
super();
this.myObject = myObject;
}
@Override
public void print() {
System.out.print("hello!");
myObject.print();
System.out.println();
}
}
package 装饰模式;
public class DecoratorB implements MyInterface{
MyInterface myObject;
public DecoratorB(MyInterface myObject) {
super();
this.myObject = myObject;
}
@Override
public void print() {
// TODO Auto-generated method stub
System.out.print("my ");
myObject.print();
}
}
------------------------------------
package 装饰模式;
public interface MyInterface {
void print();
}
--------------------------------
package 装饰模式;
public class Myclass implements MyInterface{
/**装饰模式
* 1)抽象构件角色(Component):定义一个抽象接口MyInterface,以规范准备接收附加责任的对象。
2)具体构件角色(Concrete Component):这是被装饰者Myclass,定义一个将要被装饰增加功能的类。
3)装饰角色(Decorator):持有一个构件对象的实例a,b,并定义了抽象构件定义的接口。
4)具体装饰角色(Concrete Decorator):负责给构件添加增加的功能
* @param args
*
*/
public static void main(String args[]){
//输出my hello world
MyInterface a = new DecoratorB(new DecoratorA(new Myclass()));
a.print();
//输出hello world
a=new DecoratorA(new Myclass());
a.print();
//输出my world
MyInterface b=new DecoratorB(new Myclass());
b.print();
}
public void print(){
System.out.print("world ");
};
}