抽象工厂模式可以用来生产不同产品族的全部产品。(对于新增加的产品,无能为力;但是支持增加产品族)
抽象工厂模式其实是工厂方法模式的升级版本,在有多个业务品种和分类时,通过抽象工厂模式产生需要的对象是一种非常好的解决方案。
首先创建发动机引擎的接口与不同层次引擎的实现类:
public interface Engine {
void run();
void start();
}
//高端引擎
class LuxuryEngine implements Engine{
@Override
public void run() {
System.out.println("转的快!");
}
@Override
public void start() {
System.out.println("启动快!可以自动启停!");
}
}
//低端引擎
class LowEngine implements Engine{
@Override
public void run() {
System.out.println("转的慢!");
}
@Override
public void start() {
System.out.println("启动慢!");
}
}
创建座椅接口与不同层次座椅的实现类:
public interface Seat {
void massage();
}
class LuxurySeat implements Seat {
@Override
public void massage() {
System.out.println("可以自动按摩!");
}
}
class LowSeat implements Seat {
@Override
public void massage() {
System.out.println("不能按摩!");
}
}
创建轮胎接口与不同层次轮胎的实现类:
public interface Tyre {
void revolve();
}
class LuxuryTyre implements Tyre {
@Override
public void revolve() {
System.out.println("旋转不磨损!");
}
}
class LowTyre implements Tyre {
@Override
public void revolve() {
System.out.println("旋转磨损快!");
}
}
创建CarFactory工厂接口:
public interface CarFactory {
Engine createEngine();
Seat createSeat();
Tyre createTyre();
}
针对不同层次的汽车,就要使用不同层次的汽车工厂类来创建,继承CarFactory接口即可:
public class LuxuryCarFactory implements CarFactory {
@Override
public Engine createEngine() {
return new LuxuryEngine();
}
@Override
public Seat createSeat() {
return new LuxurySeat();
}
@Override
public Tyre createTyre() {
return new LuxuryTyre();
}
}
public class LowCarFactory implements CarFactory {
@Override
public Engine createEngine() {
return new LowEngine();
}
@Override
public Seat createSeat() {
return new LowSeat();
}
@Override
public Tyre createTyre() {
return new LowTyre();
}
}
最后,客户端实现:
public class Client {
public static void main(String[] args) {
CarFactory factory = new LuxuryCarFactory();
Engine e = factory.createEngine();
e.run();
e.start();
}
}