什么是空对象模式
用一个空对象取代 null,有效的防止空指针报错。这样的空对象可以在数据不可用的时候提供自定义的错误提示
示例图
图片.png示例场景
通过简单工厂模式根据鞋子品牌制造不同类型和鞋码的鞋子,当传递的品牌信息找不到时返回指定的错误提示(空对象)
示例代码
1.创建Shoe接口类
public interface Shoe {
//判断是否为null
boolean isNull();
//展示信息
void show();
}
2.创建NullShoe空对象鞋子类
public class NullShoe implements Shoe {
@Override
public boolean isNull() {
return true;
}
@Override
public void show() {
System.out.println("制造鞋子失败,请查看参数是否正确");
}
}
3.创建ConcreteShoe具体鞋子对象实现类
public class ConcreteShoe implements Shoe {
private String shoeType;// 鞋子类型
private int shoeSize; //鞋子尺寸
public ConcreteShoe(String shoeType, int shoeSize) {
this.shoeType = shoeType;
this.shoeSize = shoeSize;
}
@Override
public boolean isNull() {
return false;
}
@Override
public void show() {
System.out.println("鞋子类型为:"+shoeType+"--------------鞋子尺寸为:"+shoeSize+"码");
}
}
4.创建ShoeFactory生产鞋子工厂类
public class ShoeFactory {
//根据品牌创建鞋子
public Shoe findBrand(String brand) {
Shoe shoe = null;
switch (brand) {
case "anta":
shoe = new ConcreteShoe("运动鞋", 40);
break;
case "lining":
shoe = new ConcreteShoe("板鞋", 42);
break;
default:
shoe = new NullShoe();
break;
}
return shoe;
}
}
5.创建client启动类
public class Client {
public static void main(String[] args) {
ShoeFactory shoeFactory = new ShoeFactory();
Shoe shoe = shoeFactory.findBrand("anta");
shoe.show();
Shoe shoe2 = shoeFactory.findBrand("lining");
shoe2.show();
Shoe shoe3 = shoeFactory.findBrand("xxx");
// if(shoe3.isNull()){
// System.out.println("参数信息错误");
// return;
// }
shoe3.show();
}
}
6.运行结果
图片.png
网友评论