装饰模型传递不了component

代码

Component

public abstract class Component {

public String FilePath;

public abstract String operation();}

ConcreteComponent

public class ConcreteComponent extends Component{

    public ConcreteComponent(String FilePath) {
        this.FilePath = FilePath;
        // TODO Auto-generated constructor stub
    }

Decorator

public  abstract class Decorator extends Component {

    public Component c; 


    public Decorator(Component c) {
        // TODO Auto-generated constructor stub

        this.c = c;
    }

    @Override
    public String operation() {
        // TODO Auto-generated method stub


        return "";
    }

}

Bugfix

public class bugfix extends Decorator {

public bugfix(Component c) {
    // TODO Auto-generated constructor stub

    super(c);
}
public String operation()
{
    String done = super.operation();

    //to do here
    return done + "bugfix";
    }

}

BankEnhanced

public class BankEnhanced extends Decorator{

    public BankEnhanced(Component c) {

        // TODO Auto-generated constructor stub
        super(c);
    }
    public String operation()
    {
        String done = super.operation();
        //todo here

        return done + "enhanced";
    }
}

main

    String strFilePath = txtFilePath.getText();

    Component c = new ConcreteComponent(strFilePath);

    Decorator d = new bugfix(c);

    if(chkBankEnhanced.isSelected())
    {               
        System.out.println("Enhanced");
        Decorator d = new BankEnhanced(d);

    }

    d.operation();
    
    
    
    

当chkBankEnhanced.isSelected()true,d.c.FilePath 就是null.

我没看出来哪里有问题,谢谢大家指教了,谢谢。

阅读 1.7k
2 个回答

包裹形式是

c = new bugfix(c);

d.c.FilePath当然是null,因为d变成BankEnhanced类型,它的d.c是bugfix类型,而不是ConcreteComponent类型。bugfix类型的FilePath 从来都没有被赋值过,所以当然等于null。

component都被正确传递了,没有被传递的是FilePath,FilePath和component是两个不同的field,不相干。在ConcreteComponent类型构造方法中有this.FilePath = FilePath;所以能传递FilePath,而bugfix类型及其基类Decorator没有传递FilePath。

你只要在bugfix或者Decorator的构造器中加入this.FilePath = FilePath;就可以让FilePath传递过来。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏