设计模式之装饰模式(Decorator)

场景

普通人跑步,跳高,举重很普通。
现在需要使用装备变成钢铁侠,3项指标成倍扩大

Man接口

public interface Man {

    void run();

    int highJump();

    int weightlifting();
}

normal man

public class NormalMan implements Man {
    @Override
    public void run() {
        System.out.println("Normal man run.");
    }

    @Override
    public int highJump() {
        System.out.println("Normal man heigh jump 1m.");
        return 1;
    }

    @Override
    public int weightlifting() {
        System.out.println("Normal man weightlifting 30KG.");
        return 30;
    }
}

iron man

public class IronMan implements Man {

    private Man normalMan;

    public IronMan(Man normalMan) {
        this.normalMan = normalMan;
    }

    @Override
    public void run() {
        normalMan.run();
        System.out.println("upgrade iron man speed 1000m/s");
    }

    @Override
    public int highJump() {
        System.out.println("upgrade iron man highJump "+normalMan.highJump()*100+"m.");
        return normalMan.highJump()*100;
    }

    @Override
    public int weightlifting() {
        System.out.println("upgrade iron man weightlifting "+normalMan.weightlifting()*100+" KG");
        return normalMan.weightlifting()*100;
    }
}

测试

 @Test
    public void decorator(){
        Man normalMan = new NormalMan();
        normalMan.run();
        normalMan.highJump();
        normalMan.weightlifting();

        System.out.println("==============");
        Man ironMan = new IronMan(normalMan);
        ironMan.run();
        ironMan.highJump();
        ironMan.weightlifting();
    }

类图
设计模式之装饰模式(Decorator)
适用性

  • 动态且透明地向各个对象添加职责,即不影响其他对象
  • 对于可以撤回的责任
  • 通过子类扩展是不切实际的。有时可能会有大量独立扩展,并会产生大量子类以支持每种组合。或者类定义可能隐藏或不可用于子类化

相关文章:

  • 2021-04-14
  • 2021-10-20
  • 2021-10-18
  • 2021-07-24
  • 2021-11-03
  • 2021-07-05
  • 2022-02-02
  • 2022-12-23
猜你喜欢
  • 2021-05-23
  • 2021-12-08
  • 2021-11-17
相关资源
相似解决方案