父类决定实例的生成方式,但不决定要生成的具体的类,具体的处理全部交给子类负责。
将生成实例的框架和实际负责生成实例的类解耦。
从而实现不管我们需要什么样的产品和工厂,他们的实例生成方式已经由框架里面的抽象类决定了,他们只需要使用子类去实现满足不同场景需求的产品具体生成。
小案例
Factory.java
package framework;
/**
* @Author:DarknessShadow
* @description:工厂,用来生成产品和注册产品
* @date 2020/5/11 13:46
*/
public abstract class Factory {
public final Product create(String owner) {
Product p = createProduct(owner);
registerProduct(p);
return p;
}
protected abstract Product createProduct(String owner);
protected abstract void registerProduct(Product product);
}
Product.java
package framework;
/**
* @Author:DarknessShadow
* @description:产品父类
* @date 2020/5/11 13:46
*/
public abstract class Product {
public abstract void use();
}
IDCardFactory.java
package idcard;
import framework.Factory;
import framework.Product;
import java.util.HashMap;
import java.util.Map;
/**
* @Author:DarknessShadow
* @description:继承工厂类,完成IDCard类实例产生的具体生成操作
* @date 2020/5/11 13:47
*/
public class IDCardFactory extends Factory {
private Map<String,Integer> owners = new HashMap<>();
private int index = 0;
@Override
protected Product createProduct(String owner) {
return new IDCard(owner);
}
@Override
protected void registerProduct(Product product) {
owners.put(((IDCard) product).getOwner(), index);
((IDCard) product).setId(index);
this.index ++;
}
public Map<String, Integer> getOwners() {
return owners;
}
}
IDCard.java
package idcard;
import framework.Product;
/**
* @Author:DarknessShadow
* @description:IDCard类是产品Product类的子类
* @date 2020/5/11 13:47
*/
public class IDCard extends Product {
private String owner;
private int id;
IDCard(String owner) {
System.out.println("制作" + owner + "的ID卡。");
this.owner = owner;
}
@Override
public void use() {
System.out.println("使用" + owner + "的ID卡,所对应的编号为:" + id );
}
public String getOwner() {
return owner;
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
}
Main.java
import framework.Factory;
import framework.Product;
import idcard.IDCardFactory;
/**
* @Author:DarknessShadow
* @description:主测试程序
* @date 2020/5/11 13:47
*/
public class Main {
public static void main(String[] args) {
Factory factory = new IDCardFactory();
Product card1 = factory.create("小明");
Product card2 = factory.create("小红");
Product card3 = factory.create("小话");
card1.use();
card2.use();
card3.use();
}
}