Java工廠模式的使用步驟如下:
public interface Product {
void doSomething();
}
public class ConcreteProduct implements Product {
@Override
public void doSomething() {
System.out.println("Do something in ConcreteProduct");
}
}
public class ConcreteFactory implements Factory {
@Override
public Product createProduct() {
return new ConcreteProduct();
}
}
public class Client {
public static void main(String[] args) {
Factory factory = new ConcreteFactory();
Product product = factory.createProduct();
product.doSomething();
}
}
通過這樣的方式,工廠模式將創建具體對象的邏輯封裝在工廠類中,客戶端只需要通過工廠類來創建產品對象,而無需直接依賴具體的產品類。這樣可以提高代碼的靈活性和可維護性,將對象的創建和使用解耦。