Decorator模式如何在Java中工作?

时间:2013-10-27 17:06:51

标签: java decorator

我试图了解Decorator Pattern。以下是我试图了解其工作原理的代码。

public static void main(String[] args)
    {
        Room myRoom =  new CurtainDecorator(new ColorDecorator(new SimpleRoom()));
        System.out.println(myRoom.showRoom());

    }

以下是我的具体类

public class SimpleRoom implements Room{

    @Override
    public String showRoom()
    {
        return "show room";
    }
}

下面是我的抽象装饰器类

public abstract class RoomDecorator implements Room{

    public Room roomReference;

    @Override
    public String showRoom()
    {
        return roomReference.showRoom();
    }
}

下面是我的装饰器实现1

public class ColorDecorator extends RoomDecorator{

    @Override
    public String showRoom()
    {
        return  addColors(); //How does showRoom() method gets invoked here?
    }

    public ColorDecorator(Room room)
    {
        this.roomReference = room;
    }

    public String addColors()
    {
        return  "Blue";
    }
}

下面是我的装饰器实现2

public class CurtainDecorator extends RoomDecorator{


    public CurtainDecorator(Room room)
    {
        this.roomReference = room;
    }

    @Override
    public String showRoom()
    {
        return this.roomReference.showRoom() + addCurtains();  //What will showRoom method invoke?
    }


public String addCurtains()
{
    return "Curtain";
}

}

输出是 - BlueCurtain

我的问题放在评论中..

1 个答案:

答案 0 :(得分:1)

最后你有: CurtainDecorator(REF = ColorDecorator(REF = SimpleRoom)))

当你从main调用showRoom时,它会调用CurtainDecorator的方法,然后首先转到它的引用(在这种情况下是ColorDecorator)输出'Blue',然后CurtainDecorator将它添加到'Curtain'中。