定义
抽象工厂模式提供一个创建一系列相关产品的接口,抽象工厂模式通常通过工厂模式来实现
优点
- 与工厂模式类似,抽象工厂模式客户端无需关注具体的产品生产细节
- 将一系列的产品族统一到一起创建
缺点
- 规定了所有可能被创建的产品集合,产品族中扩展新的产品困难,需要扩展抽象工厂接口
代码实现
在上篇的博客中,我们通过了Nike/Addidas的鞋工厂来举例说明了工厂模式。这次我们进行些扩展,众所周知,Nike/Addidas不只是生产鞋子,还生产衣服。我们创建Nike/Addidas的衣服工厂来生产各自品牌的衣服。但是有个要求,Nike生产的一定是Nike的衣服和鞋子,Addidas生产的一定是Addidas的衣服和鞋子。
public abstract class Shoe {
protected abstract String name();
}
public class NikeShoe extends Shoe {
@Override
protected String name() {
return "nike shoe";
}
}
public class AddidasShoe extends Shoe {
@Override
protected String name() {
return "addidas shoe";
}
}
public abstract class Clothes {
protected abstract String name();
}
public class NikeClothes extends Clothes {
@Override
protected String name() {
return "nike clothes";
}
}
public class AddidasClothes extends Clothes {
@Override
protected String name() {
return "addidas clothes";
}
}
public abstract class BrandFactory {
protected abstract Shoe getShoe();
protected abstract Clothes getClothes();
}
public class NikeBrandFactory extends BrandFactory {
@Override
protected Shoe getShoe() {
return new NikeShoe();
}
@Override
protected Clothes getClothes() {
return new NikeClothes();
}
}
public class AddidasBrandFactory extends BrandFactory {
@Override
protected Shoe getShoe() {
return new AddidasShoe();
}
@Override
protected Clothes getClothes() {
return new AddidasClothes();
}
}