【设计模式】工厂方法模式实例
程序员文章站
2024-01-05 11:32:46
...
// 1. 抽象产品
interface Product {
void info();
}
// 2. 具体产品
class ProductA implements Product {
@Override
public void info() {
System.out.println("ProductA");
}
}
class ProductB implements Product {
@Override
public void info() {
System.out.println("ProductB");
}
}
// 3. 抽象工厂
interface Factory {
Product getProduct();
}
// 4. 具体工厂
class ProductAFactory implements Factory {
@Override
public Product getProduct() {
return new ProductA();
}
}
class ProductBFactory implements Factory {
@Override
public Product getProduct() {
return new ProductB();
}
}
public class FactoryMethod {
public static void main(String[] args) {
Factory factory = new ProductAFactory();
Product product = null;
product = factory.getProduct();
product.info(); // ProductA
factory = new ProductBFactory();
product = factory.getProduct();
product.info(); // // ProductA
}
}