在Java中實(shí)現(xiàn)抽象工廠模式,可以按照以下步驟進(jìn)行:
public interface Product {
void operation();
}
public class ConcreteProductA implements Product {
@Override
public void operation() {
System.out.println("具體產(chǎn)品A的操作");
}
}
public class ConcreteProductB implements Product {
@Override
public void operation() {
System.out.println("具體產(chǎn)品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中實(shí)現(xiàn)抽象工廠模式??蛻舳送ㄟ^抽象工廠創(chuàng)建產(chǎn)品,而具體的產(chǎn)品由具體工廠類創(chuàng)建。這樣可以實(shí)現(xiàn)產(chǎn)品和工廠的解耦,使得客戶端在使用產(chǎn)品時(shí),不需要關(guān)心具體的產(chǎn)品類。