设计模式-工厂方法设计模式
工厂方法模式
工厂方法模式让一个类的实例化延迟到子类
public class FactoryMethodTest {
public static void main(String[] args) {
Application application = new ConcreteProductA();
//Application application = new ConcreteProductB();
Product product = application.getObject();
product.method();
}
}
interface Product {
public void method();
}
class ProductA implements Product {
@Override
public void method() {
System.out.println("ProductA 实现的方法");
}
}
class ProductB implements Product {
@Override
public void method() {
System.out.println("ProductB 实现的方法");
}
}
abstract class Application {
//相当于工厂方法
abstract Product createProduct();
public Product getObject(){
return createProduct();
}
}
//子类实现
class ConcreteProductA extends Application {
@Override
Product createProduct() {
return new ProductA();
}
}
//子类实现
class ConcreteProductB extends Application {
@Override
Product createProduct() {
return new ProductB();
}
}