|
|
|
|
@ -0,0 +1,80 @@
|
|
|
|
|
package main.java;
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 主类 - 演示简单工厂模式的使用
|
|
|
|
|
* 遵循最少知道原则,只与工厂类和产品抽象类交互
|
|
|
|
|
*/
|
|
|
|
|
public class Main {
|
|
|
|
|
/**
|
|
|
|
|
* 主方法,程序入口点
|
|
|
|
|
* @param args 命令行参数
|
|
|
|
|
*/
|
|
|
|
|
public static void main(String[] args) {
|
|
|
|
|
System.out.println("===== 简单工厂模式演示 =====");
|
|
|
|
|
|
|
|
|
|
// 使用工厂创建产品A
|
|
|
|
|
try {
|
|
|
|
|
System.out.println("\n1. 创建并使用产品A:");
|
|
|
|
|
Product productA = Factory.createProduct(Factory.PRODUCT_TYPE_A);
|
|
|
|
|
displayProductInfo(productA);
|
|
|
|
|
} catch (Exception e) {
|
|
|
|
|
System.err.println("Error: " + e.getMessage());
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 使用工厂创建产品B
|
|
|
|
|
try {
|
|
|
|
|
System.out.println("\n2. 创建并使用产品B:");
|
|
|
|
|
Product productB = Factory.createProduct(Factory.PRODUCT_TYPE_B);
|
|
|
|
|
displayProductInfo(productB);
|
|
|
|
|
} catch (Exception e) {
|
|
|
|
|
System.err.println("Error: " + e.getMessage());
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 测试无效产品类型
|
|
|
|
|
try {
|
|
|
|
|
System.out.println("\n3. 测试无效产品类型:");
|
|
|
|
|
Product invalidProduct = Factory.createProduct("C");
|
|
|
|
|
displayProductInfo(invalidProduct);
|
|
|
|
|
} catch (Exception e) {
|
|
|
|
|
System.err.println("Expected exception: " + e.getMessage());
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 测试安全工厂方法
|
|
|
|
|
System.out.println("\n4. 测试安全工厂方法:");
|
|
|
|
|
Product safeProduct = Factory.createProductSafe("D");
|
|
|
|
|
if (safeProduct == null) {
|
|
|
|
|
System.out.println("安全工厂正确处理了无效产品类型");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 新增测试用例:测试产品类型大小写不敏感性
|
|
|
|
|
try {
|
|
|
|
|
System.out.println("\n5. 测试产品类型大小写不敏感性:");
|
|
|
|
|
// 测试小写产品类型
|
|
|
|
|
Product productALower = Factory.createProduct("a");
|
|
|
|
|
System.out.println("使用小写'a'创建产品:");
|
|
|
|
|
displayProductInfo(productALower);
|
|
|
|
|
|
|
|
|
|
// 测试混合大小写产品类型
|
|
|
|
|
Product productBMixed = Factory.createProduct("B");
|
|
|
|
|
System.out.println("使用大写'B'创建产品:");
|
|
|
|
|
displayProductInfo(productBMixed);
|
|
|
|
|
} catch (Exception e) {
|
|
|
|
|
System.err.println("Error: " + e.getMessage());
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
System.out.println("\n===== 演示结束 =====");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 显示产品信息
|
|
|
|
|
* @param product 产品实例
|
|
|
|
|
*/
|
|
|
|
|
private static void displayProductInfo(Product product) {
|
|
|
|
|
if (Factory.isValidProduct(product)) {
|
|
|
|
|
System.out.println("产品名称: " + product.getName());
|
|
|
|
|
System.out.println("使用结果: " + product.use());
|
|
|
|
|
} else {
|
|
|
|
|
System.out.println("无效产品");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|