这是个关于命令模式的练习。用学生类来生成一个链表,然后在根据学号和姓名来进行查询。要求就是,两种查询方式都要写成命令模式。但是我这里为了让查询方式能够适应变长链表,我把链表的生成方法也写成了命令模式。但是运行的时候出现了问题。
[code="java"]
//Student.java文件
package studentcommand1;
public class Student
{
public int num;
public String name;
public int score;
public Student next;
public Student(int nu,String na,int sc,Student ne)
{
this.num=nu;
this.name=na;
this.score=sc;
this.next=ne;
}
public void setNext(Student t)
{
this.next=t;
}
public Student getNext()
{
return next;
}
}[/code]
[code="java"]
//Receiver.java文件
package studentcommand1;
public class Receiver
{
public Student stu;
public int length=1;
public void add()
{
Student stu=new Student(1,"stu1",(int)(Math.random()*100),null);
for(int i=1;i<10;i++)
{
stu.setNext(new Student(i+1,"stu"+(i+1),(int)(Math.random()*100),stu));
stu=stu.getNext();
length++;
}
}
public void find1(int nu)
{
Student st=stu;
for(int i=0;i<length;i++)
{
if(nu==st.num)
{
System.out.println("学号为"+nu+"的学生成绩为:"+st.score);
break;
}
else
{
st=st.next;
}
}
}
public void find2(String na)
{
Student st=stu;
for(int i=0;i<length;i++)
{
if(na.equals(st.name))
{
System.out.println("姓名为"+na+"的学生成绩为:"+st.score);
break;
}
else
{
st=st.next;
}
}
}
}
[/code]
[code="java"]
//Command.java文件
package studentcommand1;
public abstract class Command
{
protected Receiver receiver;
public Command(Receiver receiver)
{
this.receiver=receiver;
}
public abstract void execute();
}
[/code]
[code="java"]
//ConcreteCommand1.java文件
package studentcommand1;
public class ConcreteCommand1 extends Command
{
public Receiver receiver;
public ConcreteCommand1(Receiver receiver)
{
super(receiver);
}
@Override
public void execute()
{
receiver.add();
}
}
[/code]
另外的两个命令是调用文件就不详细写了,就是把上面这个execute()里的receiver.add()分别改成receiver.find1(2)和receiver.find2("stu3")。
[code="java"]
//Invoker.java文件
package studentcommand1;
public class Invoker {
private Command command;
private void setCommand(Command command)
{
this.command=command;
}
public void executeCommand()
{
command.execute();
}
public static void main(String[] args)
{
Receiver receiver=new Receiver();
Invoker invoker=new Invoker();
invoker.setCommand(new ConcreteCommand1(receiver));
invoker.executeCommand();
invoker.setCommand(new ConcreteCommand2(receiver));
invoker.executeCommand();
invoker.setCommand(new ConcreteCommand3(receiver));
invoker.executeCommand();
}
}
[/code]
整个代码就这样了,但是运行的时候就提示第一条链表生成的命令invoker.executeCommand()引用的空指针,Debug的时候发现是add()方法跟本没有被调用,并且Debug的进入方法也进不了方法里面,这是什么原因啊。我看编译器也提示说什么使用了过时的什么东东,没搞懂啊!
public class ConcreteCommand1 extends Command
{
public Receiver receiver;
public ConcreteCommand1(Receiver receiver)
{
super(receiver);
}
}
你的super(receiver)初始化了父类的receiver,并没有初始化子类的receiver
所以就会报空指针了