繁体   English   中英

java - 如何在Java运行时更改具体装饰器中的变量

[英]How do I change the variable in a concrete decorator during run-time in java

这是情况。

带有 JLabel label的 Items 抽象类,以及通过将 JLabel 添加到 JPanel 来在屏幕上显示项目的display()函数:

public abstract class Items {

    public JLabel label;

    // to add label to panel (display on screen)
    public abstract void display(JPanel panel);
}

一个具体的实现:

public class ConcreteItem extends Items {

    public ConcreteItem() {
        // set the label of concrete item
        ImageIcon icon = new ImageIcon(new URL("https://..."));
        this.label = new JLabel(icon);
    }
    @Override
    public void display(JPanel panel) {
        panel.add(this.label);
    }
}

装饰师:

public abstract class ItemDecorator extends Items {

    public Items decoratedItem;

    public ItemDecorator(Items decoratedItem){
        super();
        this.decoratedItem = decoratedItem;
    }

    @Override
    public void display(JPanel panel) {
        this.item.display(panel);
    }

}

和混凝土装饰器:

public class ConcreteDecorator extends ItemDecorator {

    public ConcreteDecorator(Items decoratedItem) {
        super(decoratedItem);

        // set the label of concrete decorator
        ImageIcon icon = new ImageIcon(new URL("https://..."));
        this.label = new JLabel(icon);
    }

    @Override
    public void display(JPanel panel) {
        super.display(panel);
        panel.add(this.label); // add label of concrete decorator to the screen
    }
}

和客户端类:

public class Client {
    public Client() {

        Jpanel panel = new JPanel();

        // create item with decorators (these are created somewhere else, furthur being returned to Client class)
        ConcreteItem concreteItem = new ConcreteItem();
        ConcreteDecorator decorator = new ConcreteDecorator(concreteItem);

        // and this is the only stuff in Client class
        Items item = decorator;

        // display all elements on screen
        item.display(panel);
    }
}

因此,当我创建一个由ConcreteDecorator装饰的Items对象时, display()函数应该将所有标签添加到面板。 我想在运行时将 ConcreteDecorator 中标签的可见性设置为false ,即label.setVisible(false) ,以便将其从屏幕上删除。 如何从只有item对象的 Client 类执行此操作?

由于flag是一个公共字段,您可以在可以访问Items实例的任何地方更改它,例如:

public class ConcreteDecorator extends ItemDecorator {

    public ConcreteDecorator(Items item) {
        super(item);
    }

    @Override
    public void display() {
        item.flag = false; // <<< change flag here
        super.display();
        System.out.print("Adding decorators to Item...");
    }
}

除了装饰者模式,你应该有更严格的可见性; 尽可能使用privateprotected的。

由于flag是一个公共字段,您应该能够从Client类中调用它:

item.flag = false;

虽然有点奇怪的类层次结构......

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM