在Java中實現抽象工廠模式,可以按照以下步驟進行:
public interface Product {
void operation();
}
public class ConcreteProductA implements Product {
@Override
public void operation() {
System.out.println("具體產品A的操作");
}
}
public class ConcreteProductB implements Product {
@Override
public void operation() {
System.out.println("具體產品B的操作");
}
}
public abstract class AbstractFactory {
public abstract Product createProduct();
}
public class ConcreteFactoryA extends AbstractFactory {
@Override
public Product createProduct() {
return new ConcreteProductA();
}
}
public class ConcreteFactoryB extends AbstractFactory {
@Override
public Product createProduct() {
return new ConcreteProductB();
}
}
public class Client {
public static void main(String[] args) {
AbstractFactory factoryA = new ConcreteFactoryA();
Product productA = factoryA.createProduct();
productA.operation();
AbstractFactory factoryB = new ConcreteFactoryB();
Product productB = factoryB.createProduct();
productB.operation();
}
}
通過以上步驟,就可以在Java中實現抽象工廠模式。客戶端通過抽象工廠創建產品,而具體的產品由具體工廠類創建。這樣可以實現產品和工廠的解耦,使得客戶端在使用產品時,不需要關心具體的產品類。