commit
8539647d0a
@ -0,0 +1,12 @@
|
||||
package src.main.java;
|
||||
|
||||
/**
|
||||
* 具体产品A
|
||||
* 实现产品接口的具体类
|
||||
*/
|
||||
public class ConcreteProductA implements Product {
|
||||
@Override
|
||||
public void operation() {
|
||||
System.out.println("ConcreteProductA performing operation");
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,12 @@
|
||||
package src.main.java;
|
||||
|
||||
/**
|
||||
* 具体产品B
|
||||
* 实现产品接口的具体类
|
||||
*/
|
||||
public class ConcreteProductB implements Product {
|
||||
@Override
|
||||
public void operation() {
|
||||
System.out.println("ConcreteProductB performing operation");
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,24 @@
|
||||
package src.main.java;
|
||||
|
||||
/**
|
||||
* 工厂类
|
||||
* 根据参数创建不同的具体产品实例
|
||||
*/
|
||||
public class Factory {
|
||||
/**
|
||||
* 创建产品的静态方法
|
||||
* @param type 产品类型
|
||||
* @return 产品实例
|
||||
*/
|
||||
public static Product createProduct(String type) {
|
||||
if (type == null) {
|
||||
return null;
|
||||
}
|
||||
if (type.equalsIgnoreCase("A")) {
|
||||
return new ConcreteProductA();
|
||||
} else if (type.equalsIgnoreCase("B")) {
|
||||
return new ConcreteProductB();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,26 @@
|
||||
package src.main.java;
|
||||
|
||||
/**
|
||||
* 测试类
|
||||
* 验证简单工厂模式的实现
|
||||
*/
|
||||
public class FactoryTest {
|
||||
public static void main(String[] args) {
|
||||
// 测试创建ConcreteProductA
|
||||
Product productA = Factory.createProduct("A");
|
||||
System.out.println("Testing Product A:");
|
||||
productA.operation();
|
||||
|
||||
// 测试创建ConcreteProductB
|
||||
Product productB = Factory.createProduct("B");
|
||||
System.out.println("\nTesting Product B:");
|
||||
productB.operation();
|
||||
|
||||
// 测试无效类型
|
||||
Product invalidProduct = Factory.createProduct("C");
|
||||
System.out.println("\nTesting Invalid Product:");
|
||||
if (invalidProduct == null) {
|
||||
System.out.println("Invalid product type, returned null");
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,12 @@
|
||||
package src.main.java;
|
||||
|
||||
/**
|
||||
* 产品接口
|
||||
* 定义所有产品共有的操作
|
||||
*/
|
||||
public interface Product {
|
||||
/**
|
||||
* 产品的操作方法
|
||||
*/
|
||||
void operation();
|
||||
}
|
||||
Loading…
Reference in new issue