代码文件

main
李千程 6 months ago
commit 2a1cda9e92

@ -0,0 +1,10 @@
/**
* A
*
*/
public class ConcreteProductA implements Product {
@Override
public void operation() {
System.out.println("ConcreteProductA 执行操作");
}
}

@ -0,0 +1,10 @@
/**
* B
*
*/
public class ConcreteProductB implements Product {
@Override
public void operation() {
System.out.println("ConcreteProductB 执行操作");
}
}

@ -0,0 +1,47 @@
/**
*
*
*/
public class Factory {
/**
*
* @param type
* @return
* @throws IllegalArgumentException
*/
public static Product createProduct(String type) {
if (type == null) {
throw new IllegalArgumentException("产品类型不能为空");
}
switch (type.toLowerCase()) {
case "a":
return new ConcreteProductA();
case "b":
return new ConcreteProductB();
default:
throw new IllegalArgumentException("未知的产品类型: " + type);
}
}
/**
*
* 使
*/
public static void main(String[] args) {
try {
// 创建产品A
Product productA = Factory.createProduct("A");
productA.operation();
// 创建产品B
Product productB = Factory.createProduct("B");
productB.operation();
// 测试异常情况
// Product productC = Factory.createProduct("C");
} catch (IllegalArgumentException e) {
System.err.println("错误: " + e.getMessage());
}
}
}

@ -0,0 +1,10 @@
/**
*
*
*/
public interface Product {
/**
*
*/
void operation();
}

@ -0,0 +1,46 @@
/**
*
*
*/
public class TestFactory {
public static void main(String[] args) {
System.out.println("===== 简单工厂模式测试 =====");
// 测试创建产品A
testProductCreation("A");
// 测试创建产品B
testProductCreation("B");
// 测试无效类型
System.out.println("\n测试无效产品类型:");
try {
Product invalidProduct = Factory.createProduct("C");
} catch (IllegalArgumentException e) {
System.out.println("预期的异常: " + e.getMessage());
}
// 测试null类型
System.out.println("\n测试null产品类型:");
try {
Product nullProduct = Factory.createProduct(null);
} catch (IllegalArgumentException e) {
System.out.println("预期的异常: " + e.getMessage());
}
}
/**
*
* @param type
*/
private static void testProductCreation(String type) {
System.out.println("\n创建产品类型: " + type);
try {
Product product = Factory.createProduct(type);
product.operation();
System.out.println("产品创建成功,类型: " + product.getClass().getSimpleName());
} catch (Exception e) {
System.out.println("产品创建失败: " + e.getMessage());
}
}
}
Loading…
Cancel
Save