Swing库中
AbstractButton类中
protected ButtonModel model= null;
public ButtonModel getModel() {
return model;
public void setActionCommand(String actionCommand) {
getModel().setActionCommand(actionCommand);//getModel反回了一个空指针的接口对象,并调用了其中预定义的方法。
}
ButtonModel不是类是接口:
public interface ButtonModel extends ItemSelectable
public void setActionCommand(String s);//接口中的确预定义好了setActionCommand方法。
我自己模仿这种方式建了测试类,发现会有 java.lang.NullPointerException空指针异常,那么这段代码是什么意思,又为了实现什么需要这么操作啊。
模板模式 -> 策略模式
http://yangguangfu.iteye.com/blog/815107
我的理解,ButtonModel是一个抽象基类或者接口。调用者去初始化它,而不是这个类本身。
为什么调用者初始化?因为调用者可以通过派生或者实现ButtonModel,并且重写方法,实现对这个代码的自定义。
这个在设计模式中叫做模板模式。
调用之前model肯定是要赋值的,你的是protected 那直接 对象. 赋值啊。不赋值肯定是空···
还有我觉得这里没什么策略模式 顶多了算是遵循依赖倒置原则,依赖抽象而不依赖具体