设计模式之装饰者模式

作用:代替继承 , 不破坏父类和实现类, 动态增强功能, 举个例子,  出去聚会,要穿戴打扮。旧的子类 有穿衣服这个方法, 现在要增强穿衣服 这个方法 ----新增 刮胡子, 喷香水,带领节功能。

1、基类

复制代码
/**
 * 〈一句话功能简述〉<br> 
 * 〈用户基类〉
 *
 * @author liangxing.zhu
 * @create 2018/9/14
 * @since 1.0.0
 */
public abstract class UserParty {
     void dress(){

    }
}
复制代码

2、实现类

复制代码
/**
 * 〈一句话功能简述〉<br> 
 * 〈〉
 *
 * @author liangxing.zhu
 * @create 2018/9/14
 * @since 1.0.0
 */
public class ZhangsanUserPartyTest extends UserParty {

    @Override
    void dress() {
        System.out.println("gogogogogo");

    }
}
复制代码

3 装饰器基类:

复制代码
/**
 * 〈一句话功能简述〉<br> 
 * 〈〉
 *
 * @author liangxing.zhu
 * @create 2018/9/14
 * @since 1.0.0
 */
public class DeacoratorDress extends   UserParty {

    UserParty userParty;

    public DeacoratorDress(UserParty userParty) {
        this.userParty = userParty;
    }

    @Override
    void dress() {
        this.userParty.dress();
    }
}
复制代码

4、装饰子类

复制代码
/**
 * 〈一句话功能简述〉<br> 
 * 〈〉
 *
 * @author liangxing.zhu
 * @create 2018/9/14
 * @since 1.0.0
 */
public class Lingjie extends DeacoratorDress {

    public Lingjie(UserParty userParty) {
        super(userParty);
    }

    @Override
    void dress() {
        this.userParty.dress();
        System.out.println("戴个领结");
    }
}
复制代码

5、装饰子类2

复制代码
/**
 * 〈一句话功能简述〉<br> 
 * 〈鞋子〉
 *
 * @author liangxing.zhu
 * @create 2018/9/14
 * @since 1.0.0
 */
public class GuaHuzi extends  DeacoratorDress {

    public GuaHuzi(UserParty userParty) {
        super(userParty);
    }

    @Override
    void dress() {
        System.out.println("刮胡子");
        this.userParty.dress();
    }
}
复制代码

6 测试类

复制代码
/**
 * 〈一句话功能简述〉<br> 
 * 〈〉
 *
 * @author liangxing.zhu
 * @create 2018/9/14
 * @since 1.0.0
 */
public class Test {

    public static void main(String[] args) {
        UserParty userParty1 = new DeacoratorDress(new GuaHuzi(new Lingjie(new Maozi(new Xiangshui(new ZhangsanUserPartyTest()))) ));
        userParty1.dress();
        System.out.println("张三结束了打扮=============");
        UserParty userParty2 = new DeacoratorDress(new Lingjie(new Maozi(new Xiangshui(new ZhangsanUserPartyTest()))));
        userParty2.dress();
        System.out.println("李四结束了打扮=============");
        UserParty userParty3 = new DeacoratorDress(new Maozi(new Lingjie(new Xiangshui(new ZhangsanUserPartyTest()))));
        userParty3.dress();
        System.out.println("王五结束了打扮============");
    }
}
复制代码

7 结果:

复制代码

刮胡子
gogogogogo
喷香水
戴个帽子
戴个领结
张三结束了打扮=============
gogogogogo
喷香水
戴个帽子
戴个领结
李四结束了打扮=============
gogogogogo
喷香水
戴个领结
戴个帽子
王五结束了打扮============

Process finished with exit code 0
复制代码
原文地址:https://www.cnblogs.com/zgghb/p/9651088.html