目录
1.核心本质
管理工厂的工厂,抽象工厂是一个约束。
解释:简单工厂模式,只能有一个产品,例如nike简单工厂只能生成衣物,但是实际情况还可以生产鞋,衣服。我们需要一个工厂去管理生产鞋和衣服的工厂。
-
产品等级结构 :产品等级结构即产品的继承结构,如一个抽象类是鞋子,其子类有阿迪达斯鞋子,nike鞋子,则抽象鞋与具体品牌的鞋之间构成了一个产品等级结构,抽象鞋是父类,而具体品牌的鞋是其子类。
-
产品族 :在抽象工厂模式中,产品族是指由同一个工厂生产的,位于不同产品等级结构中的一组产品,如NIKE工厂生产的nike鞋、nike衣服,nike鞋位于鞋产品等级结构中,衣服位于衣服产品等级结构中。
简单工厂和抽象工厂的核心区别:简单工厂管理一个产品等级结构,抽象工厂管理多个产品等级结构。
2.基础类
2.1 衣服接口 nike衣服 adidas衣服
//衣服接口
public interface ClothesProduct {
void height();//身高
void weight();//体重
}
//nike衣服
public class NikeClothes implements clothesProduct{
@Override
public void height() {
System.out.println("nikeClothesHeight");
}
@Override
public void weight() {
System.out.println("nikeClothesWeight");
}
}
//adidas衣服
public class AdidasClothes implements clothesProduct{
@Override
public void height() {
System.out.println("adidasClothesHeight");
}
@Override
public void weight() {
System.out.println("adidasClothesWeight");
}
}
2.2 鞋子接口 nike鞋子 adidas鞋子
//鞋子接口
public interface ShoesProduct {
void size();//鞋码
}
//nike鞋子
public class NikeShoes implements shoesProduct{
@Override
public void size() {
System.out.println("nike鞋码");
}
}
//adidas鞋子
public class AdidasShoes implements shoesProduct{
@Override
public void size() {
System.out.println("adidas鞋码");
}
}
2.3 创建抽象工厂
public interface ProductFactory {
void createShoes();
void createClothes();
}
2.4 创建nike工厂 adidas工厂
//创建nike工厂
public class NikeFactory implements productFactory{
@Override
public void createShoes() {
new nikeShoes().size();
}
@Override
public void createClothes() {
new nikeClothes().height();
new nikeClothes().weight();
}
}
//创建adidas工厂
public class AdidasFactory implements productFactory{
@Override
public void createShoes() {
new adidasShoes().size();
}
@Override
public void createClothes() {
new adidasClothes().height();
new adidasClothes().weight();
}
}
2.5 测试类
//测试类
public class Test {
public static void main(String[] args) {
NikeFactory nikeFactory = new NikeFactory();
nikeFactory.createClothes();
nikeFactory.createShoes();
AdidasFactory adidasFactory = new AdidasFactory();
adidasFactory.createClothes();
adidasFactory.createShoes();
}
}