装饰器模式(Decorator Pattern)

装饰模式通常是为了在已有功能动态的添加更多功能的一种方式,这些新加的代码通常装饰了原有类的核心职责或者主要行为。而这些新加入的东西仅仅为了满足一些只在某种特定情况下才会执行的特殊行为的需要,装饰器模式将每个要装饰的功能放在单独的类中,并让这个类包装它要装饰的对象。因此,在需要执行特殊行为时,客户代码就可以在运行时根据需要有选择地、按顺序的使用装饰器功能包装对象。有效地把类的核心职责和装饰功能区分开了。

package DesignPattern.DecoratorPattern;

public class Person {

    public Person(){
    }

    private String name;

    public Person(String name){
        this.name=name;
    }
    public void show(){}
}
package DesignPattern.DecoratorPattern;

public class Finery extends Person {

    protected Person component;

    public void decorate(Person component){
        this.component=component;
    }

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

具体装饰类

package DesignPattern.DecoratorPattern;

public class BigTrouser extends Finery {

    @Override
    public void show() {
        System.out.print("垮裤 ");
        this.component.show();
    }
}
package DesignPattern.DecoratorPattern;

public class LeatherShoes extends Finery {

    @Override
    public void show() {
        System.out.print("皮鞋 ");
        this.component.show();
    }
}
package DesignPattern.DecoratorPattern;

public class Sneaker extends Finery {

    @Override
    public void show() {
        System.out.print("运动鞋 ");
        this.component.show();
    }
}
package DesignPattern.DecoratorPattern;

public class Suit extends Finery {

    @Override
    public void show() {
        System.out.print("领带 ");
        this.component.show();
    }
}
package DesignPattern.DecoratorPattern;

public class Tshirts extends Finery {

    @Override
    public void show() {
        System.out.print("大T恤 ");
        this.component.show();
    }
}
package DesignPattern.DecoratorPattern;

public class Client {

    public static void main(String[] args){

        Person xc=new Person("小明");
        System.out.println("第一种装扮:");
        Sneaker pqx=new Sneaker();
        BigTrouser bt=new BigTrouser();
        Tshirts ts=new Tshirts();
        pqx.decorate(xc);
        bt.decorate(pqx);
        ts.decorate(bt);
        ts.show();
        System.out.println("\n第二种装扮");

        LeatherShoes px=new LeatherShoes();
        Tie ld=new Tie();
        Suit su=new Suit();
        px.decorate(xc);
        ld.decorate(px);
        su.decorate(ld);
        su.show();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值