话不多说,直接上代码
/**
* 被装饰者类
* @author 阳尚俊
*
*/
public interface Human {
public void wearCloth();
}
/**
* 被装饰者的具体实现类
* @author waf
*
*/
public class Person implements Human {
@Override
public void wearCloth() {
System.out.print("光着身体");
}
}
/**
* 装饰者抽象类
* @author waf
*
*/
public abstract class Decorator implements Human {
private Human human;
public Decorator(Human human){
this.human=human;
}
public void wearCloth(){
human.wearCloth();
}
}
/**
* 具体装饰者类 0
* @author waf
*
*/
public class Decorator_zero extends Decorator{
public Decorator_zero(Human human) {
super(human);
}
public void wearCloth(){
super.wearCloth();
System.out.print("穿衣");
}
}
/**
* 具体装饰者类 2
* @author waf
*
*/
public class Decorator_two extends Decorator {
public Decorator_two(Human human) {
super(human);
// TODO Auto-generated constructor stub
}
@Override
public void wearCloth() {
// TODO Auto-generated method stub
super.wearCloth();
System.out.print("穿上了鞋字");
}
}
/**
* 具体装饰者类 3
* @author waf
*
*/
public class Decorator_three extends Decorator {
public Decorator_three(Human human) {
super(human);
// TODO Auto-generated constructor stub
}
@Override
public void wearCloth() {
// TODO Auto-generated method stub
super.wearCloth();
System.out.print("穿靴子");
}
}
/**
* 测试类
* @author waf
*
*/
public class Test {
public static void main(String[] args) {
new Decorator_three(new Decorator_two(new Decorator_zero(new Person()))).wearCloth();
}
}
通过以上设计不难看出,其实装饰者模式的初衷就是为了解决对一类事物进行逐步修饰点缀的问题,通过常规的继承方式实现
会存在生成我多个类的繁杂事情,而这种模式完美的解决了以上问题,通过一个共有的装饰者抽象类,将被装饰者的接口通过构造器传入,
public Decorator_zero(Human human) {
super(human);
}
然而所有的装饰者类都是实现了我们的Human接口,所以每次在创建具体装饰者的时候都可以把其他具体装饰者通过构造器传入
,这样super.wearCloth()都是层层调用,最后传入接口实现对象就大功告成!
感觉自己理解的也不是很深刻,希望大家多多指教。
运行结果:
光着身体穿衣穿上了鞋字穿靴子