上篇说到简单工厂和工厂方法,她们一次只能创建一个产品,由于这种局限性,所以这里引入抽象工厂,用来完成一堆产品(产品族)的创建。
/**
* 汽车类
*
*/
class Car {
private Engine engine;
private Body body;
private Seat seat;
private Tyre tyre;
public Engine getEngine() {
return engine;
}
public void setEngine(Engine engine) {
this.engine = engine;
}
public Body getBody() {
return body;
}
public void setBody(Body body) {
this.body = body;
}
public Seat getSeat() {
return seat;
}
public void setSeat(Seat seat) {
this.seat = seat;
}
public Tyre getTyre() {
return tyre;
}
public void setTyre(Tyre tyre) {
this.tyre = tyre;
}
/**
*提供toString方便输出
*/
@Override
public String toString() {
return engine.getName() + "-" + body.getName() + "-" +seat.getName()
+ "-" + tyre.getName();
}
}
/**
*引擎类
*
*/
class Engine{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
/**
* 车身类
*
*/
class Body{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
/**
* 座位
*
*/
class Seat{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
/**
* 轮胎类
*
*/
class Tyre{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
这个汽车拥有引擎,车身,座位,和轮胎四个属性,假设现在需要高端和低端两种车,那么构造车的配件就应该分为高端和低端的。
/**
* 汽车配件工厂
*
*/
public interface Factory {
/**
* 制造引擎
*/
Engine createEngine();
/**
* 制造车身
*/
Body createBody();
/**
* 制造座位
*/
Seat createSeat();
/**
* 制造轮子
*/
Tyre createTyre();
}
具体的实现
/**
* 低端工厂
*
*/
public class LowFactory implements Factory {
@Override
public Engine createEngine() {
Engine e = new Engine();
e.setName("低端引擎就是差");
return e;
}
@Override
public Body createBody() {
Body body = new Body();
body.setName("低端车身就是难看");
return body;
}
@Override
public Seat createSeat() {
Seat seat = new Seat();
seat.setName("低端座位太硬");
return seat;
}
@Override
public Tyre createTyre() {
Tyre tyre = new Tyre();
tyre.setName("估计开几圈就坏了");
return tyre;
}
}
/**
* 高端工厂
*/
public class HighFactory implements Factory {
@Override
public Engine createEngine() {
Engine e = new Engine();
e.setName("高端引擎就是棒");
return e;
}
@Override
public Body createBody() {
Body body = new Body();
body.setName("极其华丽的车身");
return body;
}
@Override
public Seat createSeat() {
Seat seat = new Seat();
seat.setName("舒服的座位");
return seat;
}
@Override
public Tyre createTyre() {
Tyre tyre = new Tyre();
tyre.setName("绕地球五圈的轮子");
return tyre;
}
}
/**
* 测试类
*
*/
class Client {
public static void main(String[] args) {
Factory factory = new LowFactory();
//Factory factory = new HighFactory();
Car car = new Car();
car.setEngine(factory.createEngine());
car.setBody(factory.createBody());
car.setSeat(factory.createSeat());
car.setTyre(factory.createTyre());
System.out.println(car);
}
}
运行结果:低端引擎就是差-低端车身就是难看-低端座位太硬-估计开几圈就坏了