一、工厂模式简介
工厂模式主要用来屏蔽创建对象的具体过程;一般工厂模式分为三类:
- 简单工厂模式(静态工厂模式)
- 工厂方法模式
- 抽象工厂模式
二、分类介绍
- 简单工厂模式:三个组成部分
- 抽象产品(一般为接口)
- 产品实现对象(实现 1、抽象产品的实现类)
- 工厂对象(根据具体产品名创建具体的类对象(即2、产品实现对象))
demo:
//抽象 产品1
interface Product{
void hello();
}
//抽象 产品2
abstract class Product_2{
abstract void hello();
}
//抽象 产品1的具体产品
class ProductImpl implements Product{
public void hello(){
}
}
//抽象 产品2的具体产品
class Product_2Impl extends Product_2{
void hello(){
}
}
//抽象 产品1、2的具体产品的生产工厂
class Factory{
public static Product getProductImpl(String name) {
if (name.equals("productImpl"))
return new ProductImpl();
else
return null;
}
public static Product_2 getProduct_2Impl(String name){
if (name.equals("Product_2Impl"))
return new Product_2Impl();
else
return null;
}
}
- 工厂方法模式
组成部分:抽象产品、具体产品、抽象工厂、具体工厂
在简单工厂模式的基础上增加了抽象工厂,使得每类具体产品的创建由相应的具体工厂去创建
demo:
//抽象 产品1
interface Product{
void hello();
}
//抽象 产品1的具体产品
class ProductImpl implements Product{
public void hello(){
}
}
//抽象工厂
interface Factory{
Product getProduct();
}
//抽象工厂的具体实现
class FactoryImpl1 implements Factory{
@Override
public Product getProduct() {
return new ProductImpl();
}
}
- 抽象工厂模式