使用目的:自己生产产品,不依赖new方法,可以更加精细地控制产品的生产。
种类:静态工厂方法、简单工厂、抽象工厂
1、静态工厂方法
包含控制产生对象逻辑的静态方法。
//Car.java
package org.gui.dp.factory;
public class Car {
private static Car car = new Car();
Car(){}
//静态工厂方法
public static Car getInstance() {
return car;
}
}
//Test.java
package org.gui.dp.factory;
public class Test {
public static void main(String[] args) {
Car c = Car.getInstance();
Car c2 = Car.getInstance();
if(c == c2) System.out.println("same car");//单例
}
}
2、简单工厂
每一个产品对于一个工厂,相同类型产品的接口相同,工厂亦是如此。
//Moveable.java
package org.gui.dp.factory;
public interface Moveable {
void run();
}
//Car.java
package org.gui.dp.factory;
public class Car implements Moveable{
private static Car car = new Car();
Car(){}
//静态工厂方法
public static Car getInstance() {
return car;
}
public void run() {
System.out.println("冒着烟奔跑中的car.......");
}
}
//Plane.java
package org.gui.dp.factory;
public class Plane implements Moveable {
@Override
public void run() {
System.out.println("扇着翅膀前进中的plane....");
}
}
//VehicleFactory
package org.gui.dp.factory;
public abstract class VehicleFactory {
abstract Moveable create();
}
//CarFactory.java
package org.gui.dp.factory;
public class CarFactory extends VehicleFactory{
public Moveable create() {
return new Car();
}
}
//PlaneFactory.java
package org.gui.dp.factory;
public class PlaneFactory extends VehicleFactory{
public Moveable create() {
return new Plane();
}
}
3、抽象工厂
组合产品的生产。
简单工厂能在产品维度进行扩展,对于产生组合产品,容易产生工厂泛滥
//AbstractFactory.java
package org.gui.dp.factory.abstractfactory;
public abstract class AbstractFactory {
public abstract Vehicle createVehicle();
public abstract Weapon createWeapon();
public abstract Food createFood();
}
//DefaultFactory.java
package org.gui.dp.factory.abstractfactory;
public class DefaultFactory extends AbstractFactory{
@Override
public Food createFood() {
// TODO Auto-generated method stub
return new Apple();
}
@Override
public Vehicle createVehicle() {
// TODO Auto-generated method stub
return new Car();
}
@Override
public Weapon createWeapon() {
// TODO Auto-generated method stub
return new AK47();
}
}
抽象工厂的缺点:当生产组合产品的抽象工厂发生变化,所有继承的工厂均需改变
4、Spring的bean工厂
(1)基于接口的类型任意定制
(2)一定程度的生产过程定制(AOP)