设计模式之装饰者模式

设计模式之装饰者模式

装饰器模式(Decorator): 动态的给一个对象添加一些额外的职责。就扩展功能而言,Decorator模式比生成子类方式更为灵活。


需求:生活中,每天我们(Person)会选择不同的的衣服(Clothes)进行搭配穿着,去勾搭小姐姐们。人作为被装饰者,可以由不同的衣服装饰。同一个人选择不同的衣服,效果是不一样的。


那么,先定义一个人接口,展示每天穿什么。–被装饰者

/**
 * Created by ProdigalWang on 2017/7/21.
 * Component 是定义一个对象接口,可以给这些对象动态地添加职责。
 */
public interface IPerson {

  String show();
}

接着,装饰器接口,继承被装饰者,不做具体实现,由具体的子装饰器实现。–装饰器

/**
 * Decorator,装饰接口,继承了Component,从外类来扩展Component类的功能,
 * 但对于Component来说,是无需知道Decorator的存在的。
 */
public interface IClothesDecorator extends IPerson{


}

假如我们想穿大裤衩的时候,我们就去定义一个大裤衩BigTrouser –具体的装饰器

/**
 * 具体的装饰者实现类,定义具体的新的职责
 */
public class BigTrouser  implements IClothes,IClothesDecorator {
//装饰者持有被装饰者的对象。
private IPerson iPerson;

public BigTrouser(IPerson iPerson){
this.iPerson=iPerson;
}

//定义新的职责
@Override
public String clothesType() {
return "大裤衩";
}

@Override
public String size() {
return "25号";
}
//增添之后的职责
@Override
public String show() {
return iPerson.show()+ size()+clothesType();
}

}

IClothes接口,只是一个衣服规范,与这里的装饰者模式实现没有关系

public interface IClothes {
//衣服类型
String clothesType();
//衣服大小
String size();
}

这个时候,我又想穿双鞋:

public class Shoes implements IClothes,IClothesDecorator {

private IPerson iPerson;
public Shoes(IPerson iPerson){
  this.iPerson = iPerson;
}
@Override
public String clothesType() {
  return "鞋子";
}

@Override
public String size() {
  return "22码";
}

@Override
public String show() {
   return iPerson.show()+ size()+clothesType();
}
}

再来个T-恤衫:

public class Tshirts implements IClothes,IClothesDecorator {

private IPerson iPerson;

public Tshirts(IPerson iPerson){
    this.iPerson=iPerson;
}
@Override
public String clothesType() {
    return "T-恤衫";
}

@Override
public String size() {
    return "175cm";
}

@Override
public String show() {
    return iPerson.show()+ size()+clothesType();
}
}

最后,装饰者被装饰:

public class test {

public static void main(String []args){

    //声明被装饰的对象
    IPerson iPerson =new Person();

    //装饰者拿到被装饰的对象并进行装饰
    IClothesDecorator bigTrouser=new BigTrouser(iPerson);
    System.out.println(bigTrouser.show());

    IClothesDecorator shoes=new Shoes(bigTrouser);
    System.out.println(shoes.show());

    IClothesDecorator tShits=new Tshirts(shoes);
    System.out.println(tShits.show());

   //小花穿的衣服是:25号大裤衩
   //小花穿的衣服是:25号大裤衩22码鞋子
   //小花穿的衣服是:25号大裤衩22码鞋子175cmT-恤衫

   }
}

总结

在我们需要为已有功能需要扩展新的新的功能,我们可以选择修改源代码,但这无疑是有巨大的风险的,这时候我们可以使用装饰者模式解决这个矛盾,我们可以有选择新的添加新的装饰功能。这么做也符合开放-封闭原则。

源码链接

本文地址:http://blog.youkuaiyun.com/ProdigalWang/article/details/75675195

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值