国外网站 备案吗,18.ppt网站是谁做的,重庆网站设计找重庆最佳科技,最专业网站建在空对象模式#xff08;Null Object Pattern#xff09;中#xff0c;一个空对象取代 NULL 对象实例的检查。Null 对象不是检查空值#xff0c;而是反应一个不做任何动作的关系。这样的 Null 对象也可以在数据不可用的时候提供默认的行为。
在空对象模式中#xff0c;我…在空对象模式Null Object Pattern中一个空对象取代 NULL 对象实例的检查。Null 对象不是检查空值而是反应一个不做任何动作的关系。这样的 Null 对象也可以在数据不可用的时候提供默认的行为。
在空对象模式中我们创建一个指定各种要执行的操作的抽象类和扩展该类的实体类还创建一个未对该类做任何实现的空对象类该空对象类将无缝地使用在需要检查空值的地方。
实现
我们将创建一个定义操作在这里是客户的名称的 AbstractCustomer 抽象类和扩展了 AbstractCustomer 类的实体类。工厂类 CustomerFactory 基于客户传递的名字来返回 RealCustomer 或 NullCustomer 对象。NullPatternDemo 我们的演示类使用 CustomerFactory 来演示空对象模式的用法。 创建 AbstractCustomer 抽象类。
public abstract class AbstractCustomer {protected String name;public abstract boolean isNil();public abstract String getName();
}RealCustomer 继承 AbstractCustomer 对其进行扩展
public class RealCustomer extends AbstractCustomer {public RealCustomer(String name) {this.name name; }Overridepublic String getName() {return name;}Overridepublic boolean isNil() {return false;}
}NullCustomer 继承 AbstractCustomer 对其进行扩展
public class NullCustomer extends AbstractCustomer {Overridepublic String getName() {return Not Available in Customer Database;}Overridepublic boolean isNil() {return true;}
}创建 CustomerFactory 类
public class CustomerFactory {public static final String[] names {Rob, Joe, Julie};public static AbstractCustomer getCustomer(String name){for (int i 0; i names.length; i) {if (names[i].equalsIgnoreCase(name)){return new RealCustomer(name);}}return new NullCustomer();}
}使用 CustomerFactory基于客户传递的名字来获取 RealCustomer 或 NullCustomer 对象
public class NullPatternDemo {public static void main(String[] args) {AbstractCustomer customer1 CustomerFactory.getCustomer(Rob);AbstractCustomer customer2 CustomerFactory.getCustomer(Bob);AbstractCustomer customer3 CustomerFactory.getCustomer(Julie);AbstractCustomer customer4 CustomerFactory.getCustomer(Laura);System.out.println(Customers);System.out.println(customer1.getName());System.out.println(customer2.getName());System.out.println(customer3.getName());System.out.println(customer4.getName());}
}执行程序输出结果
Customers
Rob
Not Available in Customer Database
Julie
Not Available in Customer Database