我试图了解装饰器模式。下面的代码试图理解其工作方式。

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";
    }
}


下面是我的抽象Decorator类

public abstract class RoomDecorator implements Room{

    public Room roomReference;

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


以下是我的Decorator实现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";
    }
}


下面是我的Decorator实现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

我的问题放在评论中。

最佳答案

最后,您有:
CurtainDecorator(ref = ColorDecorator(ref = SimpleRoom)))

当您从main调用showRoom时,它将调用CurtainDecorator的方法,该方法首先转到输出“蓝色”的引用(在本例中为ColorDecorator),然后CurtainDecorator将其添加到“ Curtain”位。

关于java - Decorator模式在Java中如何工作?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19620838/

10-10 19:22