文章目录
目录:https://blog.youkuaiyun.com/qq_52681418/article/details/114828850
设计模式-抽象工厂模式
抽象工厂就是将具有向似功能的产品足提取为一个工厂。
假设你的工厂生产小米手机、华为手机,小米电脑、华为电脑,此时我们可以将电脑、手机进行分类。
手机:
手机接口
public interface PC { void show(); }
华为手机
public class HuaWeiPhone implements Phone { public void sun(){ System.out.println("---华为手机---"); } }
小米手机
public class XiaoMiPhone implements Phone{ public void sun(){ System.out.println("---小米手机---"); } }
电脑:
电脑接口
public interface PC { void show(); }
华为电脑
public class HuaWeiPC implements PC { public void show() { System.out.println("---华为电脑---"); } }
小米电脑
public class XiaoMiPC implements PC { public void show() { System.out.println("---小米电脑---"); } }
产品都列出来了,此时我们需要一个工厂,先不管工厂如何构造,它必须支持生产电脑和手机。抽象工厂定义后需要被手机、电脑工厂继承。
工厂:
抽象工厂:接口抽象类都行
public interface PrentFactory { PC creatPC(String pcName); Phone createPhone(String phoneName); }
手机分工厂
public class PhoneFactory implements PrentFactory{ //不生产电脑 public PC creatPC(String pcName) { return null; } public Phone createPhone(String phoneName) { if(phoneName.equals("HuaWei"))return new HuaWeiPhone(); if (phoneName.equals("XiaoMi"))return new XiaoMiPhone(); return null; } }
电脑工厂
public class PCFactory implements PrentFactory { public PC creatPC(String pcName) { if (pcName.equals("HuaWei")) return new HuaWeiPC(); if (pcName.equals("XiaoMi")) return new XiaoMiPC(); return null; } //不生产手机 public Phone createPhone(String phoneName) { return null; } }
可能你会好奇,电脑工厂、手机工厂为什么不直接写一起呢。这里是为了实现手机、PC工厂的解耦。
分工厂本身就不止一个,为了实现这些分工厂和调用者解耦,使用工厂模式来使用工厂。
你可以理解为它是一个建筑工厂,它来盖你的产品工厂
public class FactoryFactory { public PrentFactory createFactory(String factoryName){ if (factoryName.equals("pc")) return new PCFactory(); if (factoryName.equals("phone")) return new PhoneFactory(); return null; } }
开始生产:
public class Main {
public static void main(String[] args) {
FactoryFactory factoryFactory=new FactoryFactory(); //建筑队
PrentFactory prentFactory1 = factoryFactory.createFactory("pc"); //盖pc工厂
PrentFactory prentFactory2 = factoryFactory.createFactory("phone");//盖phone工厂
PC pc1=prentFactory1.creatPC("HuaWei"); //创建华为电脑
PC pc2=prentFactory1.creatPC("XiaoMi"); //创建小米电脑
Phone phone1=prentFactory2.createPhone("HuaWei"); //创建华为手机
Phone phone2=prentFactory2.createPhone("XiaoMi"); //创建小米手机
pc1.show();
pc2.show();
phone1.sun();
phone2.sun();
}
}
可以看出产品族扩展是困难的。