前言,相关联博客如下:
目录
1. 定义
抽象工厂模式就是创建一个超级工厂来创建各类工厂,这个超级工厂又叫做各类工厂的工厂。适用于系统有多个产品族。
2.抽象工厂模式的实践Demo
(故事背景还是源自简单工厂模式和工厂方法模式,见文章置顶处?)
老板跟小明和老王在讨论南北菜系的优缺点,小明认为南方的菜系精致好吃,老王则认为北方的菜系量大实惠,老板见两人都不肯罢休,就让小明去南方菜馆买了一份红烧肉和酸菜鱼回来,接着让老王去北方菜馆买一份红烧肉和酸菜鱼回来,食物对比一下。
1. 定义南北饭店的超级工厂,用来创建南方饭店工厂和北方饭店工厂
public interface SouthNorthFoodFactory {
Food getPork();
Food getFish();
}
2. 创建南方饭店和北方饭店,实现南北饭店超级工厂
public class SouthFoodFactory implements SouthNorthFoodFactory {
@Override
public Food getPork() {
return new SouthPork();
}
@Override
public Food getFish() {
return new SouthFish();
}
}
public class NorthFoodFactory implements SouthNorthFoodFactory {
@Override
public Food getPork() {
return new NorthPork();
}
@Override
public Food getFish() {
return new NorthFish();
}
}
3. 定义南方菜馆和北方的具体食物类
public class SouthPork extends Pork {
@Override
public String get() {
return "南派红烧肉";
}
}
public class SouthFish extends Fish {
@Override
public String get() {
return "南派酸菜鱼";
}
}
public class NorthPork extends Pork {
@Override
public String get() {
return "北派红烧肉";
}
}
public class NorthFish extends Fish {
@Override
public String get() {
return "北派酸菜鱼";
}
}
4.测试
public class AbstractFactoryPatternActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_abstract_factory_pattern);
TextView northPorkTv = findViewById(R.id.north_pork_tv);
TextView northFishTv = findViewById(R.id.north_fish_tv);
TextView southPorkTv = findViewById(R.id.south_pork_tv);
TextView southFishTv = findViewById(R.id.south_fish_tv);
//南方食物工厂
SouthNorthFoodFactory southFoodFactory = new SouthFoodFactory();
Food southPork = southFoodFactory.getPork();
Food southFish = southFoodFactory.getFish();
southPorkTv.setText(southPork.get());
southFishTv.setText(southFish.get());
//北方食物工厂
SouthNorthFoodFactory northFoodFactory = new NorthFoodFactory();
Food northPork = northFoodFactory.getPork();
Food northFish = northFoodFactory.getFish();
northPorkTv.setText(northPork.get());
northFishTv.setText(northFish.get());
}
}
5. 测试效果为: