抽象工厂模式
(Abstract Factory Pattern)属于创建型模式,是围绕一个超级工厂创建其他工厂。该超级工厂又称为其他工厂的工厂。
在抽象工厂模式
中,接口是负责创建一个相关对象的工厂,不需要显式指定它们的类。每个生成的工厂都能按照工厂模式提供对象。
通过使用抽象工厂模式
,可以将客户端与具体产品的创建过程解耦,使得客户端可以通过工厂接口来创建一族产品。
抽象工厂模式
包含4个核心角色:
package blog;
/**
* 摩托车
*/
public interface Motorcycle {
void by();
}
package blog;
/**
* 踏板摩托车
*/
public class Scooter implements Motorcycle{
@Override
public void by() {
System.out.println("骑着一辆踏板车");
}
}
package blog;
/**
* 弯梁摩托车
*/
public class UnderBone implements Motorcycle{
@Override
public void by() {
System.out.println("骑着一辆弯梁车");
}
}
package blog;
/**
* 汽车
*/
public interface Car {
void drive();
}
package blog;
/**
* suv
*/
public class Suv implements Car{
@Override
public void drive() {
System.out.println("开着一辆SUV");
}
}
package blog;
/**
* mpv
*/
public class Mpv implements Car{
@Override
public void drive() {
System.out.println("开着一辆MPV");
}
}
package blog;
/**
* 抽象工厂
*/
public interface AbstractFactory {
Car getCar(String type);
Motorcycle getMotorCycle(String type);
}
package blog;
/**
* 摩托车工厂
*/
public class MotorCycleFactory implements AbstractFactory {
@Override
public Car getCar(String type) {
return null;
}
@Override
public Motorcycle getMotorCycle(String type) {
try {
Class<?> aClass = Class.forName(type);
return (Motorcycle) aClass.getDeclaredConstructor().newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
package blog;
/**
* 汽车工厂
*/
public class CarFactory implements AbstractFactory {
@Override
public Car getCar(String type) {
try {
Class<?> aClass = Class.forName(type);
return (Car)aClass.getDeclaredConstructor().newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public Motorcycle getMotorCycle(String type) {
return null;
}
}
package blog;
/**
* 工厂生成器
*/
public class FactoryProducer {
public static AbstractFactory getFactory(String type) {
if ("car".equals(type)) {
return new CarFactory();
}
if ("motorcycle".equals(type)) {
return new MotorCycleFactory();
}
return null;
}
}
package blog;
public class AbstractFactoryDemo {
public static void main(String[] args) {
// 获取汽车工厂
AbstractFactory carFactory = FactoryProducer.getFactory("car");
// 获取suv
Car suv = carFactory.getCar("blog.Suv");
suv.drive();
// 获取mpv
Car mpv = carFactory.getCar("blog.Mpv");
mpv.drive();
// 获取摩托车工厂
AbstractFactory motorcycleFactory = FactoryProducer.getFactory("motorcycle");
// 获取scooter
Motorcycle scooter = motorcycleFactory.getMotorCycle("blog.Scooter");
scooter.by();
// 获取UnderBone
Motorcycle underBone = motorcycleFactory.getMotorCycle("blog.UnderBone");
underBone.by();
}
}