说到工厂方法,首先来认识一下简单工厂。简单工厂是由一个工厂对象决定创建出哪一种产品类的实例,代码实现很简单,很容易理解。
//抽象产品
abstract class Car {
private String name;
public abstract void drive();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
//具体产品
class Benz extends Car {
public void drive() {
System.out.println(this.getName() + " " + "GO");
}
}
//具体产品
class Bmw extends Car {
public void drive() {
System.out.println(this.getName() + "GO");
}
}
//简单工厂
class Drive {
public static Car createCar(String car) {
Car c = null;
if ("Benz".equalsIgnoreCase(car))
c = new Benz();
else if ("Bmw".equalsIgnoreCase(car))
c = new Bmw();
return c;
}
}
//老板(客户端)
public class Boss {
public static void main(String[] args) {
Car car = Drive.createCar("Benz");
car.setName("Benz");
car.drive();
}
}
和简单工厂相比,工厂方法提供了针对不同产品的具体的工厂,有利于将不同产品和具体工厂解耦。
首先看一下这个抽象工厂和产品
public abstract class Factory {
public final Product create(String owner) {
Product product = createProduct(owner);
registerProduct(product);
return product;
}
protected abstract Product createProduct(String owner);
protected abstract void registerProduct(Product product);
}
这里我只是象征性的添加了两个方法createProduct (), registerProduct ()
,create ()
是重点。
public abstract class Product {
public abstract void use();
}
下面是具体的工厂和产品
public class IdCardFactory extends Factory {
private List<String> owners = new ArrayList<>(10);
@Override
protected Product createProduct(String owner) {
return new IdCard(owner);
}
/**
* 相当于注册产品,可以放到一个容器中,方便使用
*/
@Override
protected void registerProduct(Product product) {
owners.add(((IdCard) product).getOwner());
}
}
public class IdCard extends Product {
private String owner;
/**
* 非public构造函数,强迫包外只能通过工厂获取
*/
IdCard(String owner) {
System.out.println("制作" + owner + "的IdCard");
this.owner = owner;
}
@Override
public void use() {
System.out.println("使用" + owner + "的IdCard");
}
public String getOwner() {
return this.owner;
}
}
客户端调用
public class Main {
public static void main(String[] args) {
Factory factory = new IdCardFactory();
Product product1 = factory.create("小明");
Product product2 = factory.create("小红");
product1.use();
product2.use();
}
}