设计模式之装饰模式(笔记)

装饰模式:动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更加灵活。装饰模式结构图如下
这里写图片描述

装饰模式适用场合:当需要给系统添加新的功能时,而这些添加的功能仅仅是为了满足一些只在某种特定情况下才会执行的特殊行为的需要,它把每个装饰的功能放在单独的类中,并让这个类包装它所要装饰的对象,因此,当需要执行特殊行为时,客户端就可以在运行时候根据需要有选择地、按顺序地使用装饰功能包装对象。

以小明搭配衣服为例。
定义一个IPerson接口

public interface IPerson {

    public void show();
}

定义一个具体对象Person

public class Person implements IPerson {

    private String name;
    public Person(){

    }
    public Person(String name){
        this.name=name;
    }

    @Override
    public void show() {
        System.out.println("打扮的"+name); 
    }
}

定义一个装饰类Finery继承IPerson

public class Finery implements IPerson{

    protected IPerson person;

    //打扮
    public void decorate(IPerson person){
        this.person=person;
    }

    @Override
    public void show() {
        if(person!=null){
            person.show();
        }       
    }
}

定义若干个具体的装饰对象,继承装饰类Finery

public class Tshirt extends Finery {

    public void show(){
        System.out.print("T恤衫,");
        super.show();
    }
}

public class Trouser extends Finery{

    public void show(){
        System.out.print("裤子,");
        super.show();
    }
}

public class LeaterShoes extends Finery{

    public void show(){
        System.out.print("皮鞋,");
        super.show();
    }
}

public class NetShoes extends Finery {

    public void show(){
        System.out.print("网鞋,");
        super.show();
    }
}

public class Suit extends Finery{

    public void show(){
        System.out.print("西装,");
        super.show();
    }
}

客户端代码

public static void main(String[] args) {

        //装饰模式
        Person person=new Person("小明");

        //第一种装扮
        System.out.println("第一种装扮 :");
        NetShoes nShoes=new NetShoes();//T恤衫
        Trouser trouser=new Trouser();//裤子
        Tshirt tshirt=new Tshirt();//网鞋

        nShoes.decorate(person);
        trouser.decorate(nShoes);
        tshirt.decorate(trouser);

        tshirt.show();

        //第二种装扮 
        System.out.println("第二种装扮 :");
        LeaterShoes lShoes=new LeaterShoes();//西装
        Trouser nTrouser=new Trouser();//裤子
        Suit suit =new Suit();//皮鞋

        lShoes.decorate(person);
        nTrouser.decorate(lShoes);
        suit.decorate(nTrouser);

        suit.show();
        }

结果显示:
第一种装扮 :
T恤衫,裤子,网鞋,打扮的小明
第二种装扮 :
西装,裤子,皮鞋,打扮的小明

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值