设计模式之工厂模式(Factory Method)
程序员文章站
2022-06-15 10:13:45
...
Intent
定义了一个创建对象的接口,但由子类决定要实例化哪个类。工厂方法把实例化操作推迟到子类。
Class Diagram
在简单工厂中,创建对象的是另一个类,而在工厂方法中,是由子类来创建对象。
下图中,Factory 有一个 doSomething() 方法,这个方法需要用到一个产品对象,这个产品对象由 factoryMethod() 方法创建。该方法是抽象的,需要由子类去实现。
Implementation
产品接口
public interface Product {
}
工厂类
public abstract class Factory {
abstract public Product factoryMethod();
public void doSomething(){
Product product = factoryMethod();
//do something with product
}
}
产品子类
public class ConcreteProduct implements Product {
public ConcreteProduct() {
System.out.println("ConcreteProduct has been created");
}
}
public class ConcreteProduct1 implements Product {
public ConcreteProduct1() {
System.out.println("ConcreteProduct1 has been created");
}
}
public class ConcreteProduct2 implements Product {
public ConcreteProduct2() {
System.out.println("ConcreteProduct2 has been created");
}
}
工厂子类
public class ConcreteFactory extends Factory {
@Override
public Product factoryMethod() {
return new ConcreteProduct();
}
}
public class ConcreteFactory1 extends Factory {
@Override
public Product factoryMethod() {
return new ConcreteProduct1();
}
}
public class ConcreteFactory2 extends Factory {
@Override
public Product factoryMethod() {
return new ConcreteProduct2();
}
}
调用
public class Client {
public static void main(String[] args) {
Factory factory = new ConcreteFactory();
Factory factory1 = new ConcreteFactory1();
Factory factory2 = new ConcreteFactory2();
factory.doSomething();
factory1.doSomething();
factory2.doSomething();
}
}