设计模式---装饰模式

今天学习了装饰模式,做个笔记。。装饰模式的基础概念可以参考:https://blog.csdn.net/cjjky/article/details/7478788

这里,就举个简单例子

孙悟空有72变,但是它平时是猴子,遇到情况下,它可以变成蝴蝶等等

因此提供的对象接口为:SunWukong

package com.designmodel.decorator;

public interface SunWukong {

    void change();
}

然后是一个具体的对象:Monkey

package com.designmodel.decorator;

public class Monkey implements SunWukong {

    public void selfIntroduce() {
        System.out.println("我是孙悟空, 我有72变");
    }
    
    @Override
    public void change() {
        System.out.println("我变");
    }

}

接下来是装饰抽象类:Transformations

package com.designmodel.decorator;

public class Transformations implements SunWukong {

    private SunWukong swk;
    
    public Transformations(SunWukong swk) {
        super();
        this.swk = swk;
    }

    @Override
    public void change() {
        swk.change();
    }

}

最后是两个具体的装饰对象:

package com.designmodel.decorator;

public class XiangFei extends Transformations  {

    public XiangFei(SunWukong swk) {
        super(swk);
    }
    
    public void nowIs() {
        System.out.println("我现在变成了香妃");
    }
}
package com.designmodel.decorator;

public class ButterFly extends Transformations {

    public ButterFly(SunWukong swk) {
        super(swk);
    }

    public void nowIs() {
        System.out.println("我现在变成了蝴蝶");
    }
}

客户端测试:

package com.designmodel.decorator;

public class MainApp {

    public static void main(String[] args) {

        Monkey monkeyKing = new Monkey();
        monkeyKing.selfIntroduce();
        System.out.println("我要变了...");
        XiangFei xf = new XiangFei(monkeyKing);
        xf.nowIs();
     System.out.println("我继续变...");
     ButterFly bf = new ButterFly(monkeyKing);
     bf.nowIs(); } }

输出结果:

我是孙悟空, 我有72变
我要变了...
我现在变成了香妃
我继续变...
我现在变成了蝴蝶

装饰模式就是这个意思。。。

猜你喜欢

转载自www.cnblogs.com/miantiaoandrew/p/9077872.html