Java设计模式之装饰者模式

装饰模式的特点:
(1) 装饰对象和真实对象有相同的接口。这样客户端对象就能以和真实对象相同的方式和装饰对象交互。
(2) 装饰对象包含一个真实对象的引用(reference)
(3) 装饰对象接受所有来自客户端的请求。它把这些请求转发给真实的对象。
(4) 装饰对象可以在转发这些请求以前或以后增加一些附加功能。这样就确保了在运行时,不用修改给定对象的结构就可以在外部增加附加的功能。在面向对象的设计中,通常是通过继承来实现对给定类的功能扩展。

在装饰模式中的各个角色有:
  (1)抽象构件(Component)角色:给出一个抽象接口,以规范准备接收附加责任的对象。
  (2)具体构件(Concrete Component)角色:定义一个将要接收附加责任的类。
  (3)装饰(Decorator)角色:持有一个构件(Component)对象的实例,并实现一个与抽象构件接口一致的接口。
  (4)具体装饰(Concrete Decorator)角色:负责给构 件对象添加上附加的责任。
  这里写图片描述
 
Component->Human

public interface Human {
     public void wear();
}

Concrete Component->Man

public class Man implements Human {

    @Override
    public void wear() {
        System.out.println("给我穿各种颜色的衣服");
    }
}

Decorator ->Decorator

public class Decorator implements Human {

    private Human human;

    public Decorator(Human human) {
        this.human = human;
    }
    @Override
    public void wear() {
        human.wear();
    }
}

Concrete Decorator->One/Two/Three

public class DecoratorOne extends Decorator {

    public DecoratorOne(Human human) {
        super(human);
    }
    public void wear() {
        super.wear();
        System.out.println("红色衣服");
    }
}
public class DecoratorTwo extends Decorator {

    public DecoratorTwo(Human human) {
        super(human);
    }
    public void wear() {
        super.wear();
        System.out.println("绿色衣服");
    }
}
public class DecoratorThree extends Decorator {
    public DecoratorThree(Human human) {
        super(human);
    }
    public void wear() {
        super.wear();
        System.out.println("蓝色衣服");
    }
}

测试类->Test

public class Test {
    public static void main(String[] args) {
//      Human huge=new Man();
//      Human one=new DecoratorOne(huge);
//      Human two=new DecoratorTwo(one);
//      Human three=new DecoratorThree(two);
        Human three=new DecoratorThree(new
                DecoratorTwo(new DecoratorOne(new Man())));

        three.wear();
    }
}

控制台输出:

给我穿各种颜色的衣服
红色衣服
绿色衣服
蓝色衣服

参考链接:
http://www.cnblogs.com/java-my-life/archive/2012/04/20/2455726.html
http://blog.youkuaiyun.com/jason0539/article/details/22713711

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值