赞
踩
1、在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。
装饰对象接受所有来自客户端的请求。它把这些请求转发给真实的对象。装饰对象可以在转发这些请求以前或以后增加一些附加功能。
比如我们去买一个肉夹馍,你可以选择加生菜、鸡蛋、鸡柳、香肠等等,一个肉夹馍加上不同的配料价格是不同的,那么我们如何去计算价钱呢?
(1)抽象组件(Component)角色:给出一个抽象类,以规范准备接收附加功能的对象。
(2)具体组件(Concrete Component)角色:定义一个将要接收附加功能的类。
(3)装饰(Decorator)角色:持有一个组件(Component)对象的实例,并实现一个与抽象构件接口一致的接口。
(4)具体装饰(Concrete Decorator)角色:负责给组件对象添加上附加的功能。
抽象组件(Component)角色:首先我们是定义一个抽象类ShouZhuaBingInterface,同时定义好基础的功能:
- public interface ShouZhuaBingInterface {
- /**
- * 描述
- *
- * @return
- */
- public String getDesc();
-
- /**
- * 手抓饼价格
- *
- * @return
- */
- public int getPrice();
- }
具体组件(Concrete Component)角色:定义一个被装饰的类,实现ShouZhuaBingInterface接口,并实现具体功能:
- public class ShouZhuaBing implements ShouZhuaBingInterface{
- @Override
- public String getDesc() {
- return "手抓饼";
- }
-
- @Override
- public int getPrice() {
- return 5;
- }
- }
装饰(Decorator)角色:定义一个装饰抽象类Deractor,实现ShouZhuaBingInterface接口,并拥有一个ShouZhuaBingInterface实例:
- public abstract class Deractor implements ShouZhuaBingInterface {
- private ShouZhuaBingInterface shouZhuaBingInterface;
-
- public Deractor(ShouZhuaBingInterface shouZhuaBingInterface) {
- this.shouZhuaBingInterface = shouZhuaBingInterface;
- }
-
- @Override
- public String getDesc() {
- return shouZhuaBingInterface.getDesc();
- }
-
- @Override
- public int getPrice() {
- return shouZhuaBingInterface.getPrice();
- }
- }
具体装饰(Concrete Decorator)角色:定义具体装饰类,继承装饰抽象类Deractor,并在其中扩展具体组件角色的功能:
鸡蛋装饰:
- public class EggDeractor extends Deractor {
- public EggDeractor(ShouZhuaBingInterface shouZhuaBingInterface) {
- super(shouZhuaBingInterface);
- }
-
- @Override
- public String getDesc() {
- String desc = "鸡蛋" + super.getDesc();
- return desc;
- }
-
- @Override
- public int getPrice() {
- int price = 2 + super.getPrice();
- return price;
- }
- }
香肠装饰:
- public class SausageDeractor extends Deractor {
- public SausageDeractor(ShouZhuaBingInterface shouZhuaBingInterface) {
- super(shouZhuaBingInterface);
- }
-
- @Override
- public String getDesc() {
- return "香肠" + super.getDesc();
- }
-
- @Override
- public int getPrice() {
- return 5 + super.getPrice();
- }
- }
现在我们可以测试一下 这个装饰者模式设计的代码有没有作用:
- public class DeractorTest {
- public static void main(String[] args) {
- ShouZhuaBingInterface shouZhuaBing = new ShouZhuaBing();
- System.out.println(shouZhuaBing.getDesc() + shouZhuaBing.getPrice());
-
- EggDeractor eggDeractor = new EggDeractor(shouZhuaBing);
- System.out.println(eggDeractor.getDesc() + eggDeractor.getPrice());
-
- SausageDeractor sausageDeractor = new SausageDeractor(shouZhuaBing);
- System.out.println(sausageDeractor.getDesc() + sausageDeractor.getPrice());
-
- SausageDeractor sausageDeractor1 = new SausageDeractor(eggDeractor);
- System.out.println(sausageDeractor1.getDesc() + sausageDeractor1.getPrice());
- }
- }
输出:
手抓饼5
鸡蛋手抓饼7
香肠手抓饼10
香肠鸡蛋手抓饼12
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。